c++序列化二叉树

这篇博客介绍了如何实现二叉树的序列化和反序列化。通过使用深度优先搜索策略,将二叉树节点的值按照某种顺序编码为字符串,然后能够根据这个字符串重建原来的二叉树结构。在编码过程中,使用了队列进行广度优先遍历,遇到空节点则插入'null'。在解码时,解析字符串并创建相应的二叉树结构。这种方法对于存储和传输二叉树数据非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述
在这里插入图片描述
题解:

/**
 * 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) {
        if(!root) return "[null]";
        queue<TreeNode*> q;
        q.push(root);
        string ret = "[";
        while(!q.empty()){
            TreeNode *tmp = q.front();
            q.pop();
            if(tmp){
                q.push(tmp->left);
                q.push(tmp->right);
                ret += to_string(tmp->val) + ",";
            }else{
                ret += "null,";
            }
        }
        ret[ret.length()-1] = ']';
        return ret;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data == "[null]") return nullptr;
        vector<string> datas;
        int l = 1 , r = 2 ;
        while(r < data.length()){
            if(data[r] == ',' || data[r] == ']'){
                datas.push_back(data.substr(l,r-l));
                l = r + 1;
                r = l ;
            }
            ++r;
        }
        TreeNode *root = new TreeNode(stoi(datas[0]));
        queue<TreeNode*> q;
        q.push(root);
        // q.push(root);
        int index = 1;
        while(!q.empty()){
            TreeNode *node = q.front();
            q.pop();
            if(node !=nullptr){
                node->left = datas[index] == "null" ? nullptr : new TreeNode(stoi(datas[index]));
                ++index;
                node->right = datas[index] == "null" ? nullptr : new TreeNode(stoi(datas[index]));
                ++index;
                q.push(node->left);
                q.push(node->right);
            }
        }
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值