Skip to content

Commit a0ef72e

Browse files
committed
solve: construct binary tree from preorder and inorder traversal
1 parent 3855d02 commit a0ef72e

File tree

1 file changed

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

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// TC: O(N) - leetcode analyze 기준
2+
// SC: O(N)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
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+
* @param {number[]} preorder
14+
* @param {number[]} inorder
15+
* @return {TreeNode}
16+
*/
17+
var buildTree = function (preorder, inorder) {
18+
if (inorder.length === 0) {
19+
return null;
20+
}
21+
22+
if (inorder.length === 1) {
23+
return new TreeNode(inorder[0]);
24+
}
25+
26+
const rootValue = preorder[0];
27+
const leftNodeLength = inorder.findIndex((value) => value === rootValue);
28+
const leftNode = buildTree(
29+
preorder.slice(1, 1 + leftNodeLength),
30+
inorder.slice(0, leftNodeLength)
31+
);
32+
const rightNode = buildTree(
33+
preorder.slice(1 + leftNodeLength),
34+
inorder.slice(leftNodeLength + 1)
35+
);
36+
return new TreeNode(rootValue, leftNode, rightNode);
37+
};

0 commit comments

Comments
 (0)