Skip to content

Commit c10adf0

Browse files
committed
Construct Binary Tree
1 parent c0e15e8 commit c10adf0

File tree

1 file changed

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

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
2+
class TreeNode {
3+
int val;
4+
TreeNode left;
5+
TreeNode right;
6+
7+
TreeNode() {}
8+
9+
TreeNode(int val) {
10+
this.val = val;
11+
}
12+
13+
TreeNode(int val, TreeNode left, TreeNode right) {
14+
this.val = val;
15+
this.left = left;
16+
this.right = right;
17+
}
18+
}
19+
20+
class Solution {
21+
22+
int preIdx = 0;
23+
24+
public TreeNode buildTree(int[] preorder, int[] inorder) {
25+
if (preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0) {
26+
return null;
27+
}
28+
29+
return build(preorder, inorder, 0, inorder.length - 1);
30+
}
31+
32+
// O(n)
33+
private TreeNode build(int[] preorder, int[] inorder, int inStart, int inEnd) {
34+
// 재귀 종료 조건
35+
// 포인터(인덱스)가 배열 길이를 넘었을
36+
if (preIdx >= preorder.length || inStart > inEnd) {
37+
return null;
38+
}
39+
40+
// preorder 첫 번째 값은 해당 부분 트리의 root 이다.
41+
int rootVal = preorder[preIdx++];
42+
TreeNode root = new TreeNode(rootVal);
43+
44+
// inOrder 배열에서 root 값의 위치를 찾는다.
45+
int rootIndex = -1;
46+
for (int i = inStart; i <= inEnd; i++) {
47+
if (inorder[i] == rootVal) {
48+
rootIndex = i;
49+
break;
50+
}
51+
}
52+
53+
// root 값을 기준으로 inorder 배열의 왼쪽 부분 배열(inStart ~ rootIndex-1)은 root의 left tree,
54+
// 오른쪽 부분 배열(rootIndex+1 ~ inEnd)은 root의 right tree 가 된다.
55+
root.left = build(preorder, inorder, inStart, rootIndex - 1);
56+
root.right = build(preorder, inorder, rootIndex + 1, inEnd);
57+
58+
return root;
59+
}
60+
}

0 commit comments

Comments
 (0)