Why time limit exceeded?


  • 0
    B

    So, I can't tell why my code gives me TLE, it looks very similar to the answers posted here, but for some reason it keeps giving me TLE on test case 44/47. Does anyone knows why?
    thx

    /**
     * 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 s = "";
            preOrder(root, s);
            return s;
        }
        void preOrder(TreeNode *root, string& s) {
            if(!root) {
                s+="#,";
                return;
            }
            s+=to_string(root->val) + ",";
            preOrder(root->left, s);
            preOrder(root->right,s);
                
        }
        vector<string> parseStringIntoArray(string s) {
            vector<string>res;
            string current = "";
            for(int i = 0; i < s.length(); i++) {
                if(s[i] == ',') {
                    res.push_back(current);
                    current = "";
                } else {
                    current += s[i];
                }
            }
            return res;
        }
        TreeNode* decode(vector<string>strings, int &pos) {
            string current = strings[pos++];
            if(current == "#") {
                return NULL;
            }
                
            TreeNode* newNode = new TreeNode(atoi(current.c_str()));
            newNode->left = decode(strings, pos);
            newNode->right = decode(strings, pos);
            return newNode;
            
        }
        TreeNode* deserialize(string data) {
           vector<string> s = parseStringIntoArray(data);
           int pos = 0;
           return decode(s, pos);
        }
    
    };
    
    // 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.