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 Q;
        Q.push(root);
        vector 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 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 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;
    }
};

你可能感兴趣的:(Serialize and Deserialize Binary Tree解题报告)