-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathConvertSortedArraytoBinarySearchTree.java
More file actions
57 lines (52 loc) · 1.46 KB
/
ConvertSortedArraytoBinarySearchTree.java
File metadata and controls
57 lines (52 loc) · 1.46 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package leetcode;
/**
* @author eko
* @date 2018/10/28 10:19 PM
*
* Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
*
* For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
*
* Example:
*
* Given the sorted array: [-10,-3,0,5,9],
*
* One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
*
* 0
* / \
* -3 9
* / /
* -10 5
*/
public class ConvertSortedArraytoBinarySearchTree {
public static void main(String[] args) {
int[] nums = {-10,-3,0,5,9};
TreeNode res = new ConvertSortedArraytoBinarySearchTree().sortedArrayToBST(nums);
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) {
return null;
}
TreeNode root = helper(nums, 0, nums.length - 1);
return root;
}
public TreeNode helper(int[] nums, int low, int high) {
if (low > high) {
return null;
}
int mid = (low + high) / 2;
TreeNode node = new TreeNode(nums[mid]);
node.left = helper(nums, low, mid - 1);
node.right = helper(nums, mid + 1, high);
return node;
}
}