leetcode 二叉樹的序列化與反序列化 前序遍歷


序列化是將一個數據結構或者對象轉換為連續的比特位的操作,進而可以將轉換后的數據存儲在一個文件或者內存中,同時也可以通過網絡傳輸到另一個計算機環境,采取相反方式重構得到原數據。

請設計一個算法來實現二叉樹的序列化與反序列化。這里不限定你的序列 / 反序列化算法執行邏輯,你只需要保證一個二叉樹可以被序列化為一個字符串並且將這個字符串反序列化為原始的樹結構。

示例:

你可以將以下二叉樹:

1
/
2 3
/
4 5

序列化為 "[1,2,3,null,null,4,5]"
提示: 這與 LeetCode 目前使用的方式一致,詳情請參閱 LeetCode 序列化二叉樹的格式。你並非必須采取這種方式,你也可以采用其他的方法解決這個問題。

說明: 不要使用類的成員 / 全局 / 靜態變量來存儲狀態,你的序列化和反序列化算法應該是無狀態的。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree

思路:按前序遍歷的方式去序列化;反序列化也是一個結點一個結點創建的過程,按照順序創建結點即可

class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res="";
        dfs1(root,res);
        return res;
    }
    void dfs1(TreeNode* root,string& res){
        if(!root){
            res+="#,";
            return;
        }
        res+=to_string(root->val);
        res+=",";
        dfs1(root->left,res);
        dfs1(root->right,res);
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int u=0;
        return dfs2(data,u);
    }
    TreeNode* dfs2(string& data,int& u){
        if(data[u]=='#'){
            u+=2;
            return NULL;
        }
        int ans=0;
        bool f=false;
        while(data[u]!=','){
            if(data[u]=='-'){
                f=true;
            }
            else{
                ans=ans*10+data[u]-'0';
            }
            u++;
        }
        u++;
        if(f)ans=-ans;
        auto root = new TreeNode(ans);
        root->left=dfs2(data,u);
        root->right=dfs2(data,u);
        return root;
    }
};

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM