C++ stack 29ms


  • 0
    T
    class Solution {
    public:
        TreeNode* str2tree(string s) {
            stack<TreeNode*> stk;
            for (int i = 0, sz = s.size(); i < sz; ++i) {
                if (s[i] == '(') continue;
                
                if (isdigit(s[i]) || s[i] == '-') {
                    int n = 0, sig = 1;
                    if (s[i] == '-') {sig = -1; ++i; }
                    while (i < sz && isdigit(s[i])) {
                        n = n * 10 + s[i++] - '0';
                    }
                    --i;
                    stk.push(new TreeNode(n*sig));
                } else {
                    TreeNode *t = stk.top(); stk.pop();
                    TreeNode *p = stk.top();
                    !p->left ? p->left = t:p->right = t;
                }
            }
            return stk.empty() ? nullptr : stk.top();
        }
    };
    

Log in to reply
 

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