Skip to content

Commit c3795ad

Browse files
committed
feat: 105. Construct Binary Tree from Preorder and Inorder Traversal
1 parent d87496a commit c3795ad

File tree

1 file changed

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

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Definition for a binary tree node.
2+
class TreeNode {
3+
val: number;
4+
left: TreeNode | null;
5+
right: TreeNode | null;
6+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
7+
this.val = val === undefined ? 0 : val;
8+
this.left = left === undefined ? null : left;
9+
this.right = right === undefined ? null : right;
10+
}
11+
}
12+
13+
// T.C: O(N)
14+
// S.C: O(N)
15+
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
16+
if (preorder.length === 0 || inorder.length === 0) {
17+
return null;
18+
}
19+
const root = new TreeNode(preorder[0]);
20+
const idx = inorder.indexOf(preorder[0]);
21+
root.left = buildTree(preorder.slice(1, idx + 1), inorder.slice(0, idx));
22+
root.right = buildTree(preorder.slice(idx + 1), inorder.slice(idx + 1));
23+
24+
return root;
25+
}
26+
27+
// Not using slice. but I think it's not necessary... first solution is more readable. and that's not so bad.
28+
// T.C: O(N)
29+
// S.C: O(N)
30+
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
31+
// this tree is consist of unique values
32+
const inorderMap = new Map<number, number>();
33+
for (const [i, val] of inorder.entries()) {
34+
inorderMap.set(val, i);
35+
}
36+
37+
function helper(preLeft: number, preRight: number, inLeft: number, inRight: number): TreeNode | null {
38+
if (preLeft > preRight) return null;
39+
40+
const rootValue = preorder[preLeft];
41+
const root = new TreeNode(rootValue);
42+
const inRootIdx = inorderMap.get(rootValue)!;
43+
44+
const leftSize = inRootIdx - inLeft;
45+
46+
root.left = helper(preLeft + 1, preLeft + leftSize, inLeft, inRootIdx - 1);
47+
root.right = helper(preLeft + leftSize + 1, preRight, inRootIdx + 1, inRight);
48+
49+
return root;
50+
}
51+
52+
return helper(0, preorder.length - 1, 0, inorder.length - 1);
53+
}

0 commit comments

Comments
 (0)