Javascript 12 line solution, beats 98%


  • 0
    C
    var buildTree = function(preorder, inorder) {
        let map = [];
        if (preorder.length===0) return null;
        for (let i=0;i<inorder.length;i++) map[inorder[i]] = i;
        return build(0, 0, preorder.length);
        function build(preS, inS, length){
            let head = new TreeNode(preorder[preS]), leftL = map[head.val]-inS;
            if (leftL) head.left = build(preS+1, inS, leftL);
            if (length-leftL-1>0) head.right = build(preS+1+leftL, inS+leftL+1, length-leftL-1);
            return head;
        }
    };

Log in to reply
 

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