【剑指offer37】【C++】序列化二叉树(困难)【BFS】

【剑指offer37】【C++】序列化二叉树(困难)【BFS】

题目

请实现两个函数,分别用来序列化和反序列化二叉树。

示例:

你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

序列化为 “[1,2,3,null,null,4,5]”

题解

思路:

力扣精选题解

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<queue>
class Codec {
public:
    string serialize(TreeNode* root) {
        string ans = "[";
        if(!root) return "[]";
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            for(int i=0;i<q.size();i++){
                TreeNode* t = q.front();
                q.pop();
                if(!t){
                    ans+="null,";
                    continue;
                }
                ans += to_string(t->val);
                ans += ",";
                q.push(t->left);
                q.push(t->right);
            }
        }
        ans.pop_back();//去掉末尾多余的逗号
        return ans+"]";
    }

    TreeNode* deserialize(string data) {
        if(data=="[]") return nullptr;
        int idx=1;
        vector<string> datas;
        for(int i=0;i<data.size();i++){//装载datas
            if(data[i]=='[') continue;
            if(data[i]==','||data[i]==']'){
                string s = data.substr(idx,i-idx);
                datas.push_back(s);
                idx = i+1;
            }
        }
        TreeNode* root = new TreeNode(stoi(datas[0]));
        int index = 1;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* node = q.front();q.pop();
            if(datas[index]!="null"){
                TreeNode* left = new TreeNode(stoi(datas[index]));
                node->left = left;
                q.push(node->left);
            }
            index++;
            if(datas[index]!="null"){
                TreeNode* right = new TreeNode(stoi(datas[index]));
                node->right = right;
                q.push(node->right);
            }
            index++;
        }
        return root;
    }
};

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

关注公众号:【THU小鱼干杂货铺】
不间断分享大厂算法题解、实习面经、学习资料等
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值