LeetCode 297. 二叉树的序列化与反序列化 C++

详细思路在注释里
1. 通过序列化,可以只使用先序遍历就可以唯一确定一颗二叉树。
2. 序列化时:空节点用"#,"表示,非空节点用其节点的val值加逗号表示。
/**
 * 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:
 
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        // 将二叉树序列化 
        string res;// 用于存储序列化后的二叉树
        dfs1(root, res);
        return res;
    }

    // res需要传入引用
    void dfs1(TreeNode* root, string& res){
        // 当节点为空,向res中存入"#,"
        if (!root){
            res += "#,";
            return;
        }
        // 向res中存入该节点的val和逗号
        res += to_string(root->val) + ',';
        dfs1(root->left, res);
        dfs1(root->right, res);
    }
 
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        // u用来记录反序列化到了二叉树的第几个节点
        int u = 0;
        return dfs2(data, u);
    }

    TreeNode* dfs2(string& data, int& u){
        // 若当前元素为'#',则说明遍历到了一个空节点,u加2,向后移动两个位置
        if (data[u] == '#'){
            u += 2;
            return NULL;
        }
        int t = 0;
        bool is_minus = false;// 用于标记data中记录的节点对应的val值的正负
        // 当遇到负号  is_minus变为true,且u再向后移动一个位置
        if (data[u] == '-'){
            is_minus = true;
            u++;
        }
        // 向后遍历,直到碰到逗号为止,获取当前节点的val
        while (data[u] != ','){
            // val可能为1位数,两位数,三位数..... 
            t = t * 10 + data[u] - '0';
            u++;// 向后移动一位
        }
        u++;
        // 若is_minus为true,需要给t乘上负一
        if (is_minus){
            t = -t;
        }

        // 根据获取到的val值t,创建一个二叉树节点
        auto root = new TreeNode(t);
        // 再获取左子树和右子树
        root->left = dfs2(data, u);
        root->right = dfs2(data, u);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值