forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortedarray2bst.java
More file actions
executable file
·35 lines (32 loc) · 962 Bytes
/
sortedarray2bst.java
File metadata and controls
executable file
·35 lines (32 loc) · 962 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num, int start, int end){
if(num==null || num.length==0 || start>end){
return null;
}
if(start==end){
TreeNode tn = new TreeNode(num[start]);
tn.left = null;
tn.right = null;
return tn;
}
int mid = start + (end-start)/2;
TreeNode tn = new TreeNode(num[mid]);
tn.left = sortedArrayToBST(num,start,mid-1);
tn.right = sortedArrayToBST(num,mid+1,end);
return tn;
}
public TreeNode sortedArrayToBST(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
return sortedArrayToBST(num,0,num.length-1);
}
}