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

        该题首先用先序遍历的思路把树转换(序列化)为字符串,这样在恢复的时候就可以根据字符串先序遍历的特点进行恢复(反序列化)。

   string int2str(int intsrc){
        stringstream ss;
        ss << intsrc;
        return ss.str();
    }
//序列化代码,先序遍历的顺序进行序列化    
    string serialize(TreeNode *root) {
        // write your code here
        string sec;
        if(root == nullptr){
            sec += "# ";
        }else{
            sec += int2str(root -> val);
            sec += " ";
            sec += serialize(root -> left);
            sec += serialize(root -> right);
        }
        return sec;
    }

    /**
     * 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.
     */
//找到序列中下一个树的节点字符串     
    int pos = 0;
    string nextString(string src){
        string result;
        if(pos < src.length()){
            if(src[pos] == ' '){
                pos++;
            }
            while(src[pos] != ' '){
                result += src[pos];
                pos++;
            }
            return result;
        }
    } 
   
    int str2int(string strsrc){
        return atoi(strsrc.c_str());
    }
//反序列化,根据字串先序遍历的特点     
    TreeNode *deserialize(string data) {
        // write your code here
        string cur = nextString(data);
        if(cur == "#"){
            return nullptr;
        }else{
            TreeNode *root = new TreeNode(str2int(cur));
            root -> left = deserialize(data);
            root -> right = deserialize(data);
            return root;
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值