Javascript 10-line, beats 92%

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

Log in to reply

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