Skip to content

Commit 9452a52

Browse files
authored
[ PS ] : Construct Binary Tree from Preorder and Inorder Traversal
1 parent 86cd574 commit 9452a52

File tree

1 file changed

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

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// 접근법
2+
// preorder: v l r
3+
// inorder: l v r
4+
5+
// preorder의 가장 첫 요소는 무조건 root
6+
// inorder에서 root보다 왼쪽에 있는 요소는 전부 left임
7+
// 여기서 중복되는 value가 없어야 하는데 문제에서 없음을 보장함
8+
// 따라서 preorder[0]을 inorder에서 찾고
9+
// 그 왼쪽, 오른쪽으로 배열을 나눠서 이걸 반복
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {number[]} preorder
21+
* @param {number[]} inorder
22+
* @return {TreeNode}
23+
*/
24+
const buildTree = function (preorder, inorder) {
25+
let preorderIndex = 0;
26+
const map = inorder.reduce((map, val, index) => {
27+
map[val] = index;
28+
return map;
29+
}, {});
30+
31+
function build(start, end) {
32+
if (start > end) {
33+
return null;
34+
}
35+
36+
const root = new TreeNode(preorder[preorderIndex++]);
37+
const index = map[root.val];
38+
39+
root.left = build(start, index - 1);
40+
root.right = build(index + 1, end);
41+
42+
return root;
43+
}
44+
45+
return build(0, inorder.length - 1);
46+
};
47+
48+
// 시간복잡도: O(n)
49+
// 공간복잡도: O(n)

0 commit comments

Comments
 (0)