zoukankan      html  css  js  c++  java
  • LeetCode 297. Serialize and Deserialize Binary Tree

    题目

    树的序列化,

    /**
     * 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 find(string s,int pos)
        {
            string str="";
            for(int i=pos;i<s.length();i++)
            {
                if(s[i]==',')
                    break;
                str +=s[i];
            }
            return str;
        }
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            
            string s="";
             fun2(root,s);
            return s;
            
        }
        
        void fun2(TreeNode* root,string& res)
        {
            if(root!=NULL)
            {
                res+=to_string(root->val);
                res+=',';
                fun2(root->left,res);
                res+=',';
                fun2(root->right,res);
            }
            else
            {
                res+='.';
            }
            
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            
            TreeNode* root=NULL;
            fun(data,root,0);
            
            return root;
            
        }
        
        int fun(string data,TreeNode* &tree,int pos)
        {
            string s = find(data,pos);
            if(s[0]=='.')
            {
                tree=NULL;
                return pos+s.length()+1;
            }
            else
            {
                tree = new TreeNode(atoi(s.c_str()));
                int x = fun(data,tree->left,pos+s.length()+1);
                int y = fun(data,tree->right,x);
                
                return y;
            }
        }         
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    
  • 相关阅读:
    bzoj3028食物 关于(1+x+x^2+x^3+x^4+...)^k的第i项系数就是c(i+k−1,k−1)的证明
    一个好玩的题--倒水
    HDU4372(第一类斯特林数)
    MySQL常用基本语句
    腾讯windows客户端一面
    腾讯PC客户端开发方向一面
    LeetCode数据库175
    Intern Day47
    Intern Day46
    Intern Day46
  • 原文地址:https://www.cnblogs.com/dacc123/p/12979608.html
Copyright © 2011-2022 走看看