-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCovertSortArrayToBST.java
More file actions
44 lines (35 loc) · 924 Bytes
/
CovertSortArrayToBST.java
File metadata and controls
44 lines (35 loc) · 924 Bytes
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
public class CovertSortArrayToBST {
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode res = helper(nums, 0, nums.length - 1);
return res;
}
public TreeNode helper(int[] nums, int low, int high) {
if(low > high) {
return null;
}
int mid = (high + low) / 2;
TreeNode res = new TreeNode(nums[mid]);
res.right = helper(nums, mid + 1, high);
res.left = helper(nums, low, mid - 1);
return res;
}
public static void main(String[] args) {
}
}