LeetCode297. Serialize and Deserialize Binary Tree

Posted 暴力的轮胎

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode297. Serialize and Deserialize Binary Tree相关的知识,希望对你有一定的参考价值。

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

如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便。

这里学会了使用 sstream 中的 输入流‘istringstream‘ 和 输出流‘ostringstream‘.

istringstream in;

in >> str;

这里没执行一次就会倒出一个string (因为in流中使用了‘ ‘空格 作为分割符, 所以可以分成很多个string)

建树的时候使用先序建立二叉树。

关键代码如下:

TreeNode* build(istringstream in){
  if(#) return null;
  else{
     new a node
     newnode -> left  = build(in)
     newnode -> right = build(in)
  }        
}
/**
 * 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:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        backtrack(root, out);
        return out.str();
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return build(in);
    }
    
private:
    void backtrack(TreeNode *rt, ostringstream &out){
        if(rt){
            out << rt -> val << " ";
            backtrack(rt -> left, out);
            backtrack(rt -> right, out);
        }else{
            out << "#"<<" ";
        }
    }
    
    // 形如: 1 # 2 其中树节点必为满树空节点用#表示。中间用空格分割。
    TreeNode* build(istringstream &in){
        string str = "";
        in >> str;
        if(str == "#" || str == ""){
            return NULL;
        }else{
            TreeNode *rt = new TreeNode(atoi(str.c_str()));
            rt -> left = build(in);
            rt -> right = build(in);
            return rt;
        }
    }
};

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

 

以上是关于LeetCode297. Serialize and Deserialize Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary T

LeetCode 297: Serialize and Deserialize Binary Tree

LeetCode297. Serialize and Deserialize Binary Tree

[leetcode]297. Serialize and Deserialize Binary Tree 序列化与反序列化二叉树

297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree