Lintcode---二叉树的序列化和反序列化

设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

 注意事项

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output ofserialize as the input of deserialize, it won't check the result of serialize.

样例

给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

  3
 / \
9  20
  /  \
 15   7

我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。

你可以采用其他的方法进行序列化和反序列化。

 

    思路:在这里使用先根遍历来实现;

               本题目难点在于,里面穿插关于字符串和整数间的互相转换。
               在序列化时,空节点的表示,不同节点值之间的分割。
               在反序列化时,字符串每个字符遍历时的控制条件和操作,以及将字符串转换为整数;

    

                参考:http://blog.csdn.net/waltonhuang/article/details/51979479

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
     
    /*
    思路:感觉上用BFS更容易解决,在这里使用先根遍历来实现;
    参考:http://blog.csdn.net/waltonhuang/article/details/51979479
    本题目难点在于,里面穿插关于字符串和整数间的互相转换。
    在序列化时,空节点的表示,不同节点值之间的分割。
    在反序列化时,字符串每个字符遍历时的控制条件和操作,以及将字符串转换为整数;
    */
    
    string serialize(TreeNode *root) {
        // write your code here
        string s = "";
        writeTree(s, root);
        return s;
    }
        
        
    void writeTree(string &s, TreeNode* root){
        
        if (root == NULL){
            s += "# ";
            return;
        }
        
        s += (to_string(root->val) + ' ');
        writeTree(s, root->left);
        writeTree(s, root->right);
    }


    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    TreeNode *deserialize(string data) {
        // write your code here
        int pos = 0;
        return readTree(data, pos);
    }
    
    TreeNode* readTree(string data, int& pos){
        
        if (data[pos] == '#'){
            pos += 2;
            return NULL;
        }
        
        int nownum = 0;
        
        while (data[pos] != ' '){
            //这里' '是为了分离不同的数字;
            nownum = nownum * 10 + (data[pos] - '0');
            pos++;
        }
        
        pos++;
        TreeNode* nowNode = new TreeNode(nownum);
        
        nowNode->left = readTree(data, pos);
        nowNode->right = readTree(data, pos);
        
        return nowNode;
    }
};

 

层次遍历方法:

 

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    string serialize(TreeNode* root) {               
        string res;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){           
            int siz=que.size();        
            while(siz--){
                TreeNode* cur=que.front();
                que.pop();
                if(cur==nullptr){
                    res+="nullptr,";
                }else{
                    string str_val=to_string(cur->val)+",";
                    res+=str_val;                    
                    que.push(cur->left);
                    que.push(cur->right);            
                }                                
            }            
        }
        return res;
    
        
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    TreeNode* deserialize(string data) {
        stringstream s(data);
        string str_node;
        queue<TreeNode*> que;
        getline(s,str_node,',');
        TreeNode* root;
        if(str_node=="nullptr"){
            return nullptr;
        }else{
            int inte_node=stoi(str_node);
            root=new TreeNode(inte_node);
            que.push(root);
        }
        while(!que.empty()){
            int siz=que.size();
            while(siz--){
                TreeNode* cur=que.front();
                que.pop();                           
                if(cur!=nullptr){
                    string str_left,str_right;                                       
                    if(getline(s,str_left,',') && str_left!="nullptr"){
                        TreeNode* l=new TreeNode(stoi(str_left));
                        que.push(l);
                        cur->left=l;
                    }                    
                    if(getline(s,str_right,',') && str_right!="nullptr"){   
                        TreeNode* r=new TreeNode(stoi(str_right));
                        que.push(r);
                        cur->right=r;
                    }                      
                }
            }            
        }
        return root;
    }
};

  

 

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    string serialize(TreeNode* root) {               
        string res;
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty()){           
            int siz=que.size();        
            while(siz--){
                TreeNode* cur=que.front();
                que.pop();
                if(cur==nullptr){
                    res+="nullptr,";
                }else{
                    string str_val=to_string(cur->val)+",";
                    res+=str_val;                    
                    que.push(cur->left);
                    que.push(cur->right);            
                }                                
            }            
        }
        return res;
    
        
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    TreeNode* deserialize(string data) {
        //这里使用stringstream和getline完成了了对字符串的切分
        
        stringstream s(data);
        string str_node;
        queue<TreeNode*> que;
        getline(s,str_node,',');
        TreeNode* root;
        if(str_node=="nullptr"){
            return nullptr;
        }else{
            //如果不是nullptr,stoi()字符串转整数
            int inte_node=stoi(str_node);
            //创建根节点,并加入队列
            root=new TreeNode(inte_node);
            que.push(root);
        }
        while(!que.empty()){
            int siz=que.size();
            while(siz--){
                TreeNode* cur=que.front();
                que.pop();                           
                if(cur!=nullptr){
                    string str_left,str_right; 
                    //继续判断下一个字符串是否为nullptr,如果不是,加入队列,创建左子节点,并用根节点指向他,
                    if(getline(s,str_left,',') && str_left!="nullptr"){
                        TreeNode* l=new TreeNode(stoi(str_left));
                        que.push(l);
                        cur->left=l;
                    }                    
                    if(getline(s,str_right,',') && str_right!="nullptr"){   
                        TreeNode* r=new TreeNode(stoi(str_right));
                        que.push(r);
                        cur->right=r;
                    }                      
                }
            }            
        }
        return root;
    }
};

  

序列化时,可以根据前、中、后、层次等遍历方式将结果存下来,但是反序列化需要根据序列化的结果来进行树的构造。

 

posted @ 2017-07-03 14:31  静悟生慧  阅读(2294)  评论(0编辑  收藏  举报