Serialize and Deserialize Binary Tree_Week9

Serialize and Deserialize Binary Tree_Week9

题目:(Serialize and Deserialize Binary Tree) ←链接戳这里

题目说明:
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.

难度: Hard

解题思路:
题目意为,想办法将二叉树序列化,再根据序列重造二叉树。简单来说就是讲已经做好的树结构用自己定义的顺序(可唯一识别)序列化成一串string,这样可以很方便简单地移动数据。而该string,又可以用方法,将其重造成一棵树。
因为前序是最简单的,所以决定用前序来构造序列,到达空节点时用*号标志,这样可以简单地恢复该树。

class Codec {
public:

    string serialize(TreeNode* root) {
        //将生成的序列定义为result
        string result = "";
        //若该节点不是空节点,则加入string,并前序访问子树
        if (root != NULL) {
            result += root->val + " ";
            serialize(root->left);
            serialize(root->right);
        } else {
            //该节点是空节点,用*号标记
            result += "* ";
        }
        return result;
    }

    // 用换了istringstream参数的函数来分析更方便于是写了个deserialize2函数
    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize2(in);
    }

private:

    TreeNode* deserialize2(istringstream& in) {
        //将in流字符一个个导出成string并且自动无视空格符
        string val;
        in >> val;
        //若标记"*",则表示为空节点
        if (val =="*") {
            return NULL;
        }
        //按照前序序列构造树。
        TreeNode* root = new TreeNode((int)(val[0] -'0'));
        root->left = deserialize2(in);
        root->right = deserialize2(in);
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值