-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ2.java
66 lines (55 loc) ยท 2.26 KB
/
Q2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ch04;
/**
* 4.2. ์ต์ ํธ๋ฆฌ: ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ๋ ์ ์ ๋ฐฐ์ด, ์ค๋ณต ๊ฐ X, ๋์ด๊ฐ ์ต์๊ฐ ๋๋ ์ด์ง ํ์ ํธ๋ฆฌ ๋ง๋ค๊ธฐ
*
* #19. ์ต์ ์ด์ง ํธ๋ฆฌ: ๋ชจ๋ ๋
ธ๋์์ ์ผ์ชฝ ๋
ธ๋์ ๊ฐ์์ ์ค๋ฅธ์ชฝ ๋
ธ๋์ ๊ฐ์๊ฐ ๊ฐ์ ๊ฒฝ์ฐ. ์ผ๋จ ๋ฃจํธ์์ ์ด๋ป๊ฒ ์ผ์ชฝ, ์ค๋ฅธ์ชฝ ๊ฐ์ ๊ฐ์ ๋
ธ๋ ํ์ธ?
* #73. ๋ค์์ ์ถ๊ฐํด์ผ ํ '์ด์์ ์ธ' ์์๋ฅผ ์ฐพ์ ๋ค insertValue๋ฅผ ๋ฐ๋ณต์ ์ผ๋ก ํธ์ถ. ์ฌ๊ท ํธ์ถ ์ถ์ฒ.
* #116. ๋ฐฐ์ด์ด ์ฃผ์ด์ก์ ๋ ์ต์ ํธ๋ฆฌ๋ฅผ ๋ฐํํ๋ createMinimalTree. ๋ฃจํธ์ ์ ์ฉ ๊ฐ๋ฅํ์ง?
*/
public class Q2 {
boolean[] used;
public static void main(String[] args) {
int[] nums = new int[]{1, 3, 4, 8, 9, 15, 30};
Q2 q2 = new Q2();
TreeNode result1 = q2.createMinimalTree(nums);
TreeNode result2 = q2.solution_createMinimalBST(nums);
inOrderTraversal(result1);
inOrderTraversal(result2);
}
// Solution 1. Binary Search
public TreeNode solution_createMinimalBST(int[] arr) {
return solution_createMinimalBST(arr, 0, arr.length - 1);
}
private TreeNode solution_createMinimalBST(int[] arr, int start, int end) {
if (end < start) {
return null;
}
int mid = (start + end) / 2;
TreeNode node = new TreeNode(arr[mid]);
node.left = solution_createMinimalBST(arr, start, mid - 1);
node.right = solution_createMinimalBST(arr, mid + 1, end);
return node;
}
// Method 1. Bianry Search
public TreeNode createMinimalTree(int[] nums) {
TreeNode root = insertValue(nums, 0, nums.length - 1);
return root;
}
private TreeNode insertValue(int[] nums, int left, int right) {
if (left <= right) {
int mid = left + (right - left) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = insertValue(nums, left, mid - 1);
root.right = insertValue(nums, mid + 1, right);
return root;
}
return null;
}
private static void inOrderTraversal(TreeNode node) {
if (node != null) {
inOrderTraversal(node.left);
System.out.println(node.value);
inOrderTraversal(node.right);
}
}
}