C++, Easy to understand 36ms


  • 0
    P
    class Solution {
        TreeNode* preorder(string& s, int& i) {
            if (i == s.size()) return NULL;
            int val = 0, sign = 1, n = s.size();
            if (s[i] == '-') { ++i; sign = -1; }
            while (i < n && s[i] >= '0' && s[i] <= '9') val = 10*val+s[i++]-'0';
            TreeNode* root = new TreeNode(val*sign);
    
            if (i < n && s[i] == '(') {
                root->left = preorder(s, ++i);
                ++i; // remove ')'
            }
            if (i < n && s[i] == '(') {
                root->right = preorder(s, ++i);
                ++i; // remove ')'
            }
            return root;
        }
    public:
        TreeNode* str2tree(string s) {
            int i = 0;
            return preorder(s, i);
        }
    };
    

Log in to reply
 

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