zoukankan      html  css  js  c++  java
  • 【剑指Offer】面试题37. 序列化二叉树

    题目

    请实现两个函数,分别用来序列化和反序列化二叉树。

    示例: 
    你可以将以下二叉树:

        1
       / 
      2   3
         / 
        4   5
    序列化为 "[1,2,3,null,null,4,5]"
    

    本题同【LeetCode】297. 二叉树的序列化与反序列化

    思路一:递归

    使用特殊符号(“#”)表示空树。

    代码

    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {        
            if (!root) return "#";
            return to_string(root->val) + " " + serialize(root->left) + " " + serialize(root->right);
    
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream is(data);
            return dfs(is);
        }
    
        TreeNode* dfs(istringstream &is) {
            string s;
            is >> s;
            if (s == "#") return nullptr;
            TreeNode *node = new TreeNode(stoi(s));
            node->left = dfs(is);
            node->right = dfs(is);
            return node;
        }
    };
    

    另一种写法

    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            ostringstream out;
            serialize(root, out);
            return out.str();
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream in(data);        
            return deserialize(in);
        }
        
    private:
        void serialize(TreeNode *root, ostringstream &out) {
            if (root == nullptr) {
                out << "# ";//必须有空格
                return;
            }
            out << root->val << " ";
            serialize(root->left, out);
            serialize(root->right, out);
        }
        
        TreeNode* deserialize(istringstream &in) {
            string val;
            in >> val;
            if (val == "#") {
                return nullptr;
            }
            TreeNode *root = new TreeNode(stoi(val));
            root->left = deserialize(in);
            root->right = deserialize(in);
            return root;
        }
    };
    
  • 相关阅读:
    在asp.net实现文件下载
    Insus IO Utility
    Marquee无间隙滚动(二)
    Refactoring Parameter
    How do I filtered TextBox with a Decimal (double) Data Type
    创建自己的类库
    把选中Gridview的记录显示出来
    如何取得当前网页名称
    一位老程序员十年的职场感悟
    java 跳转语句
  • 原文地址:https://www.cnblogs.com/galaxy-hao/p/12445230.html
Copyright © 2011-2022 走看看