Serialize and Deserialize Binary Tree_Week9

Serialize and Deserialize Binary Tree_Week9

题目:(Serialize and Deserialize Binary Tree) ←链接戳这里

题目说明:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

难度: Hard

解题思路:
题目意为,想办法将二叉树序列化,再根据序列重造二叉树。简单来说就是讲已经做好的树结构用自己定义的顺序(可唯一识别)序列化成一串string,这样可以很方便简单地移动数据。而该string,又可以用方法,将其重造成一棵树。
因为前序是最简单的,所以决定用前序来构造序列,到达空节点时用*号标志,这样可以简单地恢复该树。

class Codec {
public:

    string serialize(TreeNode* root) {
        //将生成的序列定义为result
        string result = "";
        //若该节点不是空节点,则加入string,并前序访问子树
        if (root != NULL) {
            result += root->val + " ";
            serialize(root->left);
            serialize(root->right);
        } else {
            //该节点是空节点,用*号标记
            result += "* ";
        }
        return result;
    }

    // 用换了istringstream参数的函数来分析更方便于是写了个deserialize2函数
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize2(in);
    }

private:

    TreeNode* deserialize2(istringstream& in) {
        //将in流字符一个个导出成string并且自动无视空格符
        string val;
        in >> val;
        //若标记"*",则表示为空节点
        if (val =="*") {
            return NULL;
        }
        //按照前序序列构造树。
        TreeNode* root = new TreeNode((int)(val[0] -'0'));
        root->left = deserialize2(in);
        root->right = deserialize2(in);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78514473
今日推荐