My Javascript Solution


  • 0
    N
    var buildTree = function(preorder, inorder) {
        if (preorder.length == 0) return null;
        
        var root = new TreeNode(preorder[0]);
        var i = 0;
        while (i < inorder.length && inorder[i] != preorder[0]) i++;
        
        // divide inorder list into left and right;
        root.left = buildTree(preorder.slice(1, i+1), inorder.slice(0, i));
        root.right = buildTree(preorder.slice(i+1, preorder.length), inorder.slice(i+1, inorder.length));
        
        return root;
        
    };
    
    

Log in to reply
 

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