其他分享
首页 > 其他分享> > 二叉树的序列化与反序列化

二叉树的序列化与反序列化

作者:互联网

我们使用二叉树的先序遍历来遍历整个树,对于空子树保存为#,恢复时也根据先序的顺序来恢复
297. Serialize and Deserialize Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    void serialize(TreeNode* root, ostringstream& out){
        if(root == nullptr) {
            out << "# ";
            return;
        }
        out << root->val << ' ';
        serialize(root->left, out);
        serialize(root->right, out);
    }
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }
    
    
    
    TreeNode* deserialize(istringstream &in){
        string data;
        in >> data;
        if(data == "#") return nullptr;
        auto root = new TreeNode(stoi(data));
        root->left = deserialize(in);
        root->right = deserialize(in);
        
        return root;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

标签:TreeNode,deserialize,data,serialize,二叉树,序列化,root,out
来源: https://www.cnblogs.com/qbits/p/11164911.html