LeetCode 每日一题 剑指 Offer 37. 序列化二叉树

题链:https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/
思路 :想复杂了,虽然必须有中序才可以唯一确定一棵树(自己写的是中序+先序)。但是,只要是同一逻辑,即可确定一个树,直接先序遍历编码即可。

注意:队列传入的时候要加引用,靠!!

/**
 * 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:
    string getStr(int x){
        if(x==0) return "0";
        string ans="";
        while(x){
            ans+='0'+x%10;
            x/=10;
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
    string ans="";
    void dfs(TreeNode* root){
        if(root==NULL){
            ans+="null,";
            return ;
        }
        ans+=getStr(root->val)+',';
        dfs(root->left);
        dfs(root->right);
    }
    int getNum(string s){
        int num = 0;
        for(int i=0;i<s.size();i++){
            num=num*10+(s[i]-'0');
        }
        //cout<<s<<" "<<num<<endl;
        return num;
    }
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ans="";
        dfs(root);
        return ans;
    }
    //加引用!!!!!!!!!!!!!!!!!!!!!!
    TreeNode * dfs1(queue<string>& q){
        string str=q.front();
        q.pop();
        if(str=="null") 
            return NULL;
        TreeNode * root = new TreeNode();
        root->val=getNum(str);
        if(!q.empty())
            root->left=dfs1(q);
        if(!q.empty())
            root->right=dfs1(q);
        return root;
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        //cout<<data<<endl;
        queue<string> q;
        int len = data.size();
        int i=0;
        while(i<len){
            int j=i;
            string s="";
            while(data[j]!=',')
                s+=data[j++];
            q.push(s);
            i=j+1;
        }
        TreeNode * root = dfs1(q);
        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、付费专栏及课程。

余额充值