Serialize and Deserialize Binary Tree解题报告

Description:

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Example:

For example, you may serialize the following tree

   1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]"
, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Link:

https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/

解题方法:

用层级遍历来序列化
格式:1 2 3 null null 4 5,即用空格隔开每个节点。
然后把每个节点压入队列,用一个bool变量来判断当前节点是不是一个右孩子节点,如果是右孩子,则把队伍头部的节点弹出。

Tips:

在反序列化时,可以用stringstream来分割字符串

Time Complexity:

O(N)

完整代码:

class Codec 
{
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) 
    {
        if(!root)
            return "";
        queue<TreeNode*> Q;
        Q.push(root);
        vector<string> builder;
        string result;
        while(!Q.empty())
        {
            TreeNode* curr = Q.front();
            Q.pop();
            if(!curr)
            {
                builder.push_back("null");
                continue;
            }
            builder.push_back(std::to_string(curr->val));
            Q.push(curr->left);
            Q.push(curr->right);
        }
        while(builder[builder.size() - 1] == "null")
            builder.pop_back();
        for(string str: builder)
        {
            result += str;
            result += " ";
        }
        result.pop_back();
        return result;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) 
    {
        vector<string> str;
        stringstream ss(data);
        string temp;
        while(ss>>temp) //用stringsteam通过空格来分割字符串
            str.push_back(temp);
        if(str.size() == 0)
            return NULL;
        TreeNode* root = new TreeNode(stoi(str[0]));
        queue<TreeNode*> Q;
        Q.push(root);
        bool isRight = false;
        for(int i = 1; i < str.size(); i++)
        {
            if(str[i] != "null")
            {
                TreeNode* curr = new TreeNode(stoi(str[i]));
                if(isRight)
                    Q.front()->right = curr;
                else
                    Q.front()->left = curr;
                Q.push(curr);
            }
            if(isRight)
                Q.pop();
            isRight = !isRight;
        }
        return root;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 14,607评论 5 6
  • 清醒时做事,糊涂时读书。大怒时睡觉,独处时思考。 再难也要坚持,再好也好淡泊。再差也要自信,再多也要节省。 --你...
    幻梦飞羽阅读 2,425评论 0 0
  • 什么是面对对象 面向对象程序设计(英语:Object-oriented programming,缩写:OOP)是种...
    LeeoZz阅读 3,110评论 0 0
  • 推开一扇窗户,慵懒的阳光照射进来,空气中略显尘埃,早晨的空气带着一丝汽油味,像睡过了头等待苏醒,雍杂繁华开始上...
    JE杰阅读 3,188评论 5 4

友情链接更多精彩内容