Serialize and Deserialize Binary Tree解題報(bào)告

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/

解題方法:

用層級(jí)遍歷來(lái)序列化
格式:1 2 3 null null 4 5,即用空格隔開(kāi)每個(gè)節(jié)點(diǎn)。
然后把每個(gè)節(jié)點(diǎn)壓入隊(duì)列,用一個(gè)bool變量來(lái)判斷當(dāng)前節(jié)點(diǎn)是不是一個(gè)右孩子節(jié)點(diǎn),如果是右孩子,則把隊(duì)伍頭部的節(jié)點(diǎn)彈出。

Tips:

在反序列化時(shí),可以用stringstream來(lái)分割字符串

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通過(guò)空格來(lái)分割字符串
            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;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,936評(píng)論 0 33
  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,681評(píng)論 5 6
  • 清醒時(shí)做事,糊涂時(shí)讀書。大怒時(shí)睡覺(jué),獨(dú)處時(shí)思考。 再難也要堅(jiān)持,再好也好淡泊。再差也要自信,再多也要節(jié)省。 --你...
    幻夢(mèng)飛羽閱讀 345評(píng)論 0 0
  • 什么是面對(duì)對(duì)象 面向?qū)ο蟪绦蛟O(shè)計(jì)(英語(yǔ):Object-oriented programming,縮寫:OOP)是種...
    LeeoZz閱讀 463評(píng)論 0 0
  • 推開(kāi)一扇窗戶,慵懶的陽(yáng)光照射進(jìn)來(lái),空氣中略顯塵埃,早晨的空氣帶著一絲汽油味,像睡過(guò)了頭等待蘇醒,雍雜繁華開(kāi)始上...
    JE杰閱讀 479評(píng)論 5 4

友情鏈接更多精彩內(nèi)容