Sharing My 19ms cpp solution


  • 0
    P
    /**
     * 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.
        
        void ser(TreeNode* root,vector<int> &nums)
        {
            if(root)
            {
                nums.push_back(root->val);
                ser(root->left,nums);
                ser(root->right,nums);
            }
        }
        
        
        string serialize(TreeNode* root) {
          
            vector<int> nums;
            ser(root,nums);
            char *p = (char*)nums.data();
            string s(p, nums.size() * sizeof(int));
    
            
            cout<<s<<endl;
            return s;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* ds(int *nums,int &index,int mini, int maxi,int n)
        {
             TreeNode* root=NULL;
                if(index>=n)
                    return root;
               
                if((nums[index])>mini && (nums[index])<maxi)
                {
                    root=new TreeNode(nums[index]);
                    index+=1;
                    
                    root->left=ds(nums,index,mini,root->val,n);
                    root->right=ds(nums,index,root->val,maxi,n);
                }
            return root;
        }
        TreeNode* deserialize(string data) {
            int mini=INT_MIN;
            int maxi=INT_MAX;
            int index=0;
             int n = data.size() / sizeof(int);
            return ds((int*)data.data(),index,mini,maxi,n);
            
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.