Recursive cpp solution using S-exp like format.quite slow,50ms


  • 0
    H
    /**
     * 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 getParenedFrom(string &data,string::iterator &it)
        {
            auto sit=it;
            int lp = 1; ++it;
            while(lp>0){
                if(*it=='('){
                    ++lp;
                }
                if(*it==')'){
                    --lp;
                }
                ++it;
            }
            return data.substr(sit-data.begin(),it-sit);
        }
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            if(root==nullptr){
                return "()";
            }
            return "(T" + to_string(root->val)
                        + serialize(root->left)
                        + serialize(root->right)
                    +")";
        }
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) 
        {
            if(data=="()"){
                return nullptr;
            }
            //(TvalSubtree1Subtree2)
            struct TreeNode* ret = (struct TreeNode*)malloc(sizeof(*ret));
            auto it = data.begin()+2;auto cit = it;
            while(*cit!='('){
                ++cit;
            }
            int num= stoi(data.substr(it-data.begin(),cit-it));
            ret->val = num;
            it = cit;
            string leftsub = getParenedFrom(data,it);
            ret->left = deserialize(leftsub);
            string rightsub = getParenedFrom(data,it);
            ret->right = deserialize(rightsub);
            return ret;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));
    

    I wonder how I can accelerate this problem,maybe using a help function to avoid string copy?


Log in to reply
 

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