Skip to content

Commit 4ac5487

Browse files
committed
solve: construct binary tree from preorder and inorder traversal
1 parent 4388ac3 commit 4ac5487

File tree

1 file changed

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

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class TreeNode {
2+
val: number;
3+
left: TreeNode | null;
4+
right: TreeNode | null;
5+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
this.val = val === undefined ? 0 : val;
7+
this.left = left === undefined ? null : left;
8+
this.right = right === undefined ? null : right;
9+
}
10+
}
11+
12+
/**
13+
* TC: O(n^2)
14+
* SC: O(n)
15+
* */
16+
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
17+
if (!preorder?.length || !inorder?.length) {
18+
return null;
19+
}
20+
21+
const rootValue = preorder[0];
22+
const root = new TreeNode(rootValue);
23+
const inorderRootIndex = inorder.indexOf(rootValue);
24+
25+
root.left = buildTree(
26+
preorder.slice(1, inorderRootIndex + 1),
27+
inorder.slice(0, inorderRootIndex),
28+
);
29+
30+
root.right = buildTree(
31+
preorder.slice(inorderRootIndex + 1),
32+
inorder.slice(inorderRootIndex + 1),
33+
);
34+
35+
return root;
36+
}

0 commit comments

Comments
 (0)