37. 序列化二叉树

剑指 Offer 37. 序列化二叉树

思路:层序遍历

serialize

  • 初始化:队列queue,结果res
  • 从队列中取出节点:
    • 若节点为空,打印字符串"null,"
    • 若节点不为空,打印对应数字,将左右子节点加入queue
  • 返回值:res

deserialize

  • 初始化:队列queue,根节点root
  • 从队列取出当前节点cur
    • 遍历字符串,若当前值不为空,构造cur->left,并加入队列
    • 遍历字符串,若当前值不为空,构造cur->right,并加入队列
  • 返回根节点
/**
 * 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);
        string ans;
        while(q.size()){
            TreeNode* cur=q.front();
            q.pop();
            if(cur==nullptr){
                ans+="null,";
            }
            else{
                ans+=to_string(cur->val)+",";
                q.push(cur->left);
                q.push(cur->right);
            }
        }
        return ans;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int i=0,j=0;
        while(j<data.size()&&data[j]!=',')++j;
        string s=data.substr(i,j-i);
        if(s=="null") return nullptr;
        TreeNode* root=new TreeNode(stoi(s));
        queue<TreeNode*> q;
        q.push(root);
        while(q.size()){
            TreeNode* cur=q.front();
            q.pop();
            i=j+1;
            j++;
            while(j<data.size()&&data[j]!=',')++j;
            string s=data.substr(i,j-i);
            if(s!="null"){
                cur->left=new TreeNode(stoi(s));
                q.push(cur->left);
            }
            i=j+1;
            j++;
            while(j<data.size()&&data[j]!=',')++j;
            s=data.substr(i,j-i);
            if(s!="null"){
                cur->right=new TreeNode(stoi(s));
                q.push(cur->right);
            }   
        }
        return root;
    }
};

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

时间复杂度 O(n)

空间复杂度 O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值