leetcode 297二叉树的序列化与反序列化

Posted joelwang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 297二叉树的序列化与反序列化相关的知识,希望对你有一定的参考价值。

技术图片

 

采用层序遍历的顺序,储存每一层的值,不存在的或者NULL值用#代替,每个位置以‘/‘结束

/**
 * 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) {
        string res;
        queue<TreeNode*> q;
        q.push(root);
        int flag=1;
        while(flag){
            flag=0;
            int k=q.size();
            for(int i=0;i<k;i++){
                TreeNode* p=q.front();
                q.pop();
                if(p==NULL){
                    res.push_back(#);
                    q.push(NULL);
                    q.push(NULL);
                }else{
                    int value=p->val;
                    if(value<0) {res.push_back(-);value=-value;}
                    stack<char> s;
                    if(value==0) s.push(0);
                    while(value){
                        int e=value%10;
                        s.push(e+0);value=value/10;
                    }
                    while(!s.empty()){
                        res.push_back(s.top());s.pop();
                    }
                    q.push(p->left);
                    q.push(p->right);
                    if(p->left||p->right) flag=1;
                }
                res.push_back(/);
            }
        }
        cout<<res<<endl;
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if(data.size()==0) return NULL;
        if(data.size()==2&&data[0]==#)return NULL;
        int len=data.size();
        vector<TreeNode*> v;
        for(int i=0;i<len;i++){
            if(data[i]==/)continue;
            TreeNode* p=NULL;
            
            if(data[i]!=#){
                int value=0;
                int flag=1;
                if(data[i]==-) {flag=-1;i++;}
                while(data[i]!=/){
                    value=10*value+data[i]-0;
                    i++;
                }
                value=flag*value;
                p=new TreeNode(value);
            }
            
            v.push_back(p);
        }
        for(int i=0;i<(v.size()-1)/2;i++){
            if(v[i]!=NULL){
                v[i]->left=v[2*i+1];
                v[i]->right=v[2*i+2];
            }
        }
        return v[0];
    }
};

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

 测试例子如下:

技术图片

样例通过为47/48,一个深度为1000的偏二叉树没有通过;

以上是关于leetcode 297二叉树的序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 297. 二叉树的序列化与反序列化

LeetCode 297 二叉树的序列化与反序列化[BFS 二叉树] HERODING的LeetCode之路

leetcode 297二叉树的序列化与反序列化

LeetCode 297. 二叉树的序列化与反序列化(bfs,二叉树,Java)

LeetCode Java刷题笔记—297. 二叉树的序列化与反序列化

LeetCode 297. 二叉树的序列化与反序列化