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));
    
  • 相关阅读:
    第一阶段SCRUM冲刺day07
    第一阶段SCRUM冲刺day06
    第一阶段SCRUM冲刺day05
    第一阶段SCRUM冲刺day04
    2020年第七周学习进度
    第一阶段SCRUM冲刺day03
    第一阶段SCRUM冲刺day02
    团队会议01
    2020年第六周学习进度
    TCP/IP Socket 的理解
  • 原文地址:https://www.cnblogs.com/dacc123/p/12979608.html
Copyright © 2011-2022 走看看