Skip to content

Commit ad17299

Browse files
committed
#253 Construct Binary Tree from Preorder and Inorder Traversal
1 parent e484116 commit ad17299

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
이 문제는 힌트의 도움을 받아서 풀었습니다.
3+
- preorder의 첫 원소는 항상 root node임
4+
- inorder에서 root node의 왼쪽의 원소들은 root node의 왼쪽 subtree, 오른쪽 원소들은 오른쪽 subtree임
5+
- 왼쪽 subtree와 오른쪽 subtree는 각각 preorder에서 연속하게 있음. (root, 왼쪽 subtree, 오른쪽 subtree 순)
6+
7+
시간 복잡도 : O(n)
8+
공간 복잡도 : O(n^2)
9+
(skewed tree의 경우, 최악의 공간 복잡도를 가짐)
10+
*/
11+
class Solution {
12+
public TreeNode buildTree(int[] preorder, int[] inorder) {
13+
if (preorder.length == 0) {
14+
return null;
15+
}
16+
if (preorder.length == 1) {
17+
return new TreeNode(preorder[0]);
18+
}
19+
int currIdx;
20+
for (currIdx = 0; currIdx < inorder.length; currIdx++) {
21+
if (inorder[currIdx] == preorder[0]) {
22+
break;
23+
}
24+
}
25+
26+
int[] lp = new int[currIdx];
27+
int[] li = new int[currIdx];
28+
int[] rp = new int[inorder.length - currIdx - 1];
29+
int[] ri = new int[inorder.length - currIdx - 1];
30+
for (int i = 0; i < currIdx; i++) {
31+
lp[i] = preorder[i + 1];
32+
li[i] = inorder[i];
33+
}
34+
for (int i = currIdx + 1; i < inorder.length; i++) {
35+
rp[i - currIdx - 1] = preorder[i];
36+
ri[i - currIdx - 1] = inorder[i];
37+
}
38+
39+
TreeNode lc = buildTree(lp, li);
40+
TreeNode rc = buildTree(rp, ri);
41+
42+
TreeNode curr = new TreeNode(preorder[0], lc, rc);
43+
44+
return curr;
45+
}
46+
}

0 commit comments

Comments
 (0)