Skip to content

Commit 741a5b6

Browse files
committed
Added constructBinaryTree solution
1 parent 587c005 commit 741a5b6

File tree

1 file changed

+17
-0
lines changed
  • construct-binary-tree-from-preorder-and-inorder-traversal

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
var buildTree = function (preorder, inorder) {
2+
// Edge case: if either preorder or inorder is empty, return null
3+
if (!preorder.length || !inorder.length) return null;
4+
5+
// The first element in preorder is the root of the tree
6+
// Find the index of the root in the inorder array
7+
const root = new TreeNode(preorder[0]);
8+
const mid = inorder.indexOf(root.val);
9+
10+
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
11+
root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1));
12+
13+
return root;
14+
};
15+
16+
// TC: O(n)
17+
// SC: O(n)

0 commit comments

Comments
 (0)