Simple JavaScript using recursion


  • 1
    var str2tree = function(s) {
        if (!s) return null;
        let paren = s.indexOf('(');
        const node = new TreeNode(parseInt(~paren ? s.substr(0, paren) : s));
        if (~paren) {
            let open = 1;
            let i = paren;
            while (open) {
                i++;
                if (s[i] === '(') open++;
                else if (s[i] === ')') open--;
            }
            node.left = str2tree(s.substring(paren + 1, i));
            paren = s.indexOf('(', i);
            if (~paren) {
                node.right = str2tree(s.substring(paren + 1, s.length - 1));
            }
        }
        return node;
    };
    

Log in to reply
 

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