-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path108.java
More file actions
58 lines (55 loc) · 1.73 KB
/
108.java
File metadata and controls
58 lines (55 loc) · 1.73 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
58
__________________________________________________________________________________________________
sample 0 ms submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums==null || nums.length==0)
return null;
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums,int low,int high){
if (low>high)
return null;
if (low == high)
return new TreeNode(nums[low]);
int mid = (low+high)/2;
TreeNode res = new TreeNode(nums[mid]);
res.left = helper(nums,low,mid-1);
res.right = helper(nums,mid+1,high);
return res;
}
}
__________________________________________________________________________________________________
sample 34432 kb submission
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return createTree(nums, 0,nums.length-1);
}
public TreeNode createTree(int[] nums, int start, int end){
if(start > end)
return null;
int mid = (start + end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = createTree(nums, start, mid -1);
root.right = createTree(nums, mid+1,end);
return root;
}
}
__________________________________________________________________________________________________