zoukankan      html  css  js  c++  java
  • 二叉树的序列化与反序列化

    我们使用二叉树的先序遍历来遍历整个树,对于空子树保存为#,恢复时也根据先序的顺序来恢复
    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));
    
  • 相关阅读:
    每日日报46
    每日日报45
    每日日报44
    每日日报43
    每日日报42
    每日日报41
    每日日报40
    每日日报之一周总结
    每日日报
    每日日报
  • 原文地址:https://www.cnblogs.com/qbits/p/11164911.html
Copyright © 2011-2022 走看看