leetcode297 二叉树的序列化与反序列化(未写代码)

还不太明白

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        if(!root) return " #";
        string ans = " "+to_string(root->val);
        return ans + serialize(root->left) + serialize(root->right); 
    }
 
    TreeNode* DFS(istringstream &is)
    {
        string str;
        is >> str;
        if(str == "#") return NULL;  //反序列化遇到#时说明以当前字符为根节点的左子树已经完了,故返回,开始反序列化右子树
        TreeNode* root = new TreeNode(stoi(str));
        root->left = DFS(is), root->right = DFS(is);
        return root;
    }
 
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream is(data);
        return DFS(is);
    }
};


参考:
https://blog.csdn.net/qq508618087/article/details/53076647

猜你喜欢

转载自blog.csdn.net/aikudexue/article/details/87796979