Skip to content

Commit a0fc24d

Browse files
committed
construct-binary-tree-from-preorder-and-inorder-traversal with solution-v1
1 parent ccd7b0d commit a0fc24d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* https://www.algodale.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
3+
*
4+
* <풀이1 기준> 시도!
5+
* - 공간 복잡도: O(N^2) - Java 에서는 Call-by-value, 메서드 호출 시 인자 값이 복사되어 전달됨 / 배열 길이에 따라서 재귀 호출 스택이 점점 깊어짐 (각 호출마다 서브 배열 생성)
6+
* - 시간 복잡도: inorder 배열에서 root 노드를 찾아가는 과정이 O(N), 그리고 이를 재귀 호출마다 반복하므로 O(N^2)
7+
*/
8+
class Solution {
9+
public TreeNode buildTree(int[] preorder, int[] inorder) {
10+
return buildTree(preorder, inorder, 0, 0, inorder.length - 1);
11+
}
12+
13+
private TreeNode buildTree(int[] preorder, int[] inorder, int rootIdx, int inorderStartIdx, int inorderEndIdx) {
14+
if (inorderStartIdx > inorderEndIdx) {
15+
return null;
16+
}
17+
18+
int rootVal = preorder[rootIdx];
19+
TreeNode root = new TreeNode(rootVal);
20+
21+
int rootIdxOnInorder = 0;
22+
for (int i = inorderStartIdx; i <= inorderEndIdx; i++) {
23+
if (inorder[i] == rootVal) {
24+
rootIdxOnInorder = i;
25+
break;
26+
}
27+
}
28+
29+
int leftLength = rootIdxOnInorder - inorderStartIdx;
30+
31+
root.left = buildTree(preorder, inorder, rootIdx + 1, inorderStartIdx, rootIdxOnInorder - 1);
32+
root.right = buildTree(preorder, inorder, rootIdx + 1 + leftLength, rootIdxOnInorder + 1, inorderEndIdx);
33+
34+
return root;
35+
}
36+
}

0 commit comments

Comments
 (0)