Skip to content

Commit 41705ae

Browse files
committed
construct-binary-tree-from-~ solution
1 parent 8d3afd7 commit 41705ae

File tree

1 file changed

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

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {number[]} preorder
11+
* @param {number[]} inorder
12+
* @return {TreeNode}
13+
*/
14+
let buildTree = function (preorder, inorder) {
15+
if (preorder.length === 0 || inorder.length === 0) {
16+
return null;
17+
}
18+
19+
// 중위 순회의 값과 인덱스를 매핑하는 Map 생성
20+
const inorderIndexMap = new Map();
21+
inorder.forEach((value, index) => {
22+
inorderIndexMap.set(value, index);
23+
});
24+
25+
// 재귀적 트리 구성 함수
26+
function build(preStart, preEnd, inStart, inEnd) {
27+
if (preStart > preEnd || inStart > inEnd) {
28+
return null;
29+
}
30+
31+
// 전위순회 배열에서 루트 노드를 얻기
32+
const rootVal = preorder[preStart];
33+
const root = new TreeNode(rootVal);
34+
35+
// 중위순회 배열에서 루트 노드의 인덱스 찾기
36+
const rootIndexInInorder = inorderIndexMap.get(rootVal);
37+
38+
// 왼쪽 서브트리 크기 계산
39+
const leftSize = rootIndexInInorder - inStart;
40+
41+
// 재귀적으로 왼쪽과 오른쪽 서브트리를 생성
42+
root.left = build(
43+
preStart + 1,
44+
preStart + leftSize,
45+
inStart,
46+
rootIndexInInorder - 1
47+
);
48+
root.right = build(
49+
preStart + leftSize + 1,
50+
preEnd,
51+
rootIndexInInorder + 1,
52+
inEnd
53+
);
54+
55+
return root;
56+
}
57+
58+
return build(0, preorder.length - 1, 0, inorder.length - 1);
59+
};
60+
61+
/*
62+
1. 시간복잡도: O(n)
63+
- 트리의 모든 노드를 한 번씩 처리해야함
64+
2. 공간복잡도: O(n)
65+
- map 저장공간, 재귀호출 스택, 트리노드 저장공간 -> O(n)
66+
*/

0 commit comments

Comments
 (0)