LeetCode 剑指 Offer 37. 序列化二叉树(bfs建树)

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

实例:
你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

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

数据范围:
题目没说.
解法:
观察样例,发现序列化时按照层序遍历来的,因此序列话的时候bfs就行了.

反序列化的时候也bfs建树即可.

这题的字符串和数字相互转换需要用到to_string(int)stoi(string).
code:
/**
 * 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) {
        queue<TreeNode*>q;
        q.push(root);
        vector<string>temp;
        while(q.size()){
            TreeNode* x=q.front();q.pop();
            if(!x){
                temp.push_back("null");
            }else{
                temp.push_back(to_string(x->val));
                q.push(x->left);
                q.push(x->right);
            }
        }
        string ans=temp[0];
        for(int i=1;i<(int)temp.size();i++){
            ans+=",";
            ans+=temp[i];
        }
        return ans;
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string s) {
        vector<string>temp;
        string x;
        for(auto i:s){
            if(i==','){
                temp.push_back(x);
                x="";
            }else{
                x+=i;
            }
        }
        temp.push_back(x);
        //
        if(temp[0]=="null")return NULL;
        TreeNode* root=new TreeNode(stoi(temp[0]));
        queue<TreeNode*>q;
        q.push(root);
        int cur=1;
        while(q.size()){
            TreeNode* x=q.front();q.pop();
            string t;
            if(cur<(int)temp.size())t=temp[cur++];
            else t="null";
            if(t=="null"){
                x->left=NULL;
            }else{
                x->left=new TreeNode(stoi(t));
                q.push(x->left);
            }
            if(cur<(int)temp.size())t=temp[cur++];
            else t="null";
            if(t=="null"){
                x->right=NULL;
            }else{
                x->right=new TreeNode(stoi(t));
                q.push(x->right);
            }
        }
        return root;
    }
};

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值