[C++] Clean Code


  • 8
    class Solution {
    public:
        TreeNode* str2tree(string s) {
            int i = 0;
            return s.size() == 0 ? nullptr : build(s, i);
        }
    
    private:
        TreeNode* build(string& s, int& i) {
            int start = i;
            if (s[i] == '-') {
                i++;
            }
            while (isdigit(s[i])) {
                i++;
            }
            
            int num = stoi(s.substr(start, i - start));
            TreeNode* node = new TreeNode(num);
            if (s[i] == '(') {
                node->left = build(s, ++i);
                i++;    // )
            }
            if (s[i] == '(') {
                node->right = build(s, ++i);
                i++;    // )
            }
            return node;
        }
    };
    

  • 1
    Z

    In build function, I think you should check whether i < s.size(). For test case "4", you may eventually check "s[1] == '(' ", which is invalid.


Log in to reply
 

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