-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertSortedArrayToBinarySearchTree.java
More file actions
40 lines (33 loc) · 1.09 KB
/
ConvertSortedArrayToBinarySearchTree.java
File metadata and controls
40 lines (33 loc) · 1.09 KB
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
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class ConvertSortedArrayToBinarySearchTree {
public static void main(String[] args) {
int[] nums = {-10,-3,0,5,9};
TreeNode head = sortedArrayToBST(nums);
System.out.println(head.val);
/*System.out.println(head.val);
System.out.println(head.left.val);
System.out.println(head.left.right.val);
System.out.println(head.right.val);
System.out.println(head.right.right.val);
*/
}
public static TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0)
return null;
return buildBST(nums, 0, nums.length - 1);
}
public static TreeNode buildBST(int[] nums, int start, int end) {
if(start > end)
return null;
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBST(nums, start, mid - 1);
root.right = buildBST(nums, mid + 1, end);
return root;
}
}