我的算法7

題目地址https://leetcode.com/problems/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.

我的代碼

/**
 * 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:
    void add_tree_to_str(TreeNode* root,string& str){
        if(root==NULL){
            str+="null,";
            return;
        }
        str+=(to_string(root->val)+",");
        add_tree_to_str(root->left,str);
        add_tree_to_str(root->right,str);
    }
    void add_str_to_tree(TreeNode* tree,string &data,int& start){
        int now=start;
        for(;start<data.size();start++)
            if(data[start]==',')break;
        if(data.substr(now,start-now)!="null"){
            tree->left=new TreeNode(atoi(data.substr(now,start-now).c_str()));
            start++;
            add_str_to_tree(tree->left,data,start);
        }
        start++;
        now=start;
        for(;start<data.size();start++)
            if(data[start]==',')break;
        if(data.substr(now,start-now)!="null"){
            tree->right=new TreeNode(atoi(data.substr(now,start-now).c_str()));
            start++;
            add_str_to_tree(tree->right,data,start);
        }

    }

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string str="";
        if(!root) return str;
        add_tree_to_str(root,str);
        return str;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        TreeNode* tree;
        if(data=="") return tree;
        int start=0;
        for(;start<data.size();start++)
            if(data[start]==',')
                break;
        string s=data.substr(0,start);
        tree=new TreeNode(atoi(s.c_str()));
        start++;
        add_str_to_tree(tree,data,start);
        return tree;
    }
};

解題思路
我的答案採用前序遍歷來轉換樹與字符串,爲方便區分左子樹與右子樹,我將所有的空節點(包括葉節點的兩個空子節點)表示爲null存儲在字符串中,於是通過遞歸調用很容易將樹轉換成字符串。前序遍歷的複雜度爲O(n)。
然後是將前序遍歷後生產的字符串轉換爲樹。仍然採用遞歸調用。對任意非空樹,先保存其根節點,然後對根節點遞歸獲取其左子樹,然後再獲取其又子樹。由於所有的空節點,包括葉節點的兩個空節點都用“null”表示在字符串中。所以遞歸到其葉節點後,遞歸過程會自然的結束。由於該過程對字符串只需順序遍歷一次,所以複雜度爲O(n)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章