Short and clean C++, use stoi() to parse num efficiently


  • 0
    C
    TreeNode* str2tree(string s) {
        int n = s.length();
        if(n == 0) return nullptr;
        stack<TreeNode*> sk;
        int i = 0;
        while(i < n) {
            if(isdigit(s[i]) || s[i] == '-') {
                int num = stoi(s.substr(i));
                i += to_string(num).length();
                auto node = new TreeNode(num);
                if(!sk.empty()){
                    if(!sk.top()->left) sk.top()->left = node;
                    else if(!sk.top()->right) sk.top()->right = node;
                } 
                sk.push(node);
            }
            if(s[i] == ')') sk.pop();
            i++;
        }
        return sk.top();
    }

Log in to reply
 

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