/**
* 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) {
if(num == null || num.length == 0){
return null;
}else if(num.length == 1){
//System.out.println(num[0]);
return new TreeNode(num[0]);
}else{
int mid = (num.length - 1) / 2;
TreeNode res = new TreeNode(num[mid]);
//System.out.println(res.val);
int[] numLeft = new int[(num.length - 1) / 2];
int[] numRight = new int[(num.length - mid - 1 )];
int pivot = (num.length - 1) / 2;
boolean hasRight = false;
for(int i = 0 ; i < num.length ; i++){
if(i < pivot){
numLeft[i] = num[i];
}else if(i > pivot){
numRight[i - pivot - 1] = num[i];
hasRight = true;
}
}
res.left = sortedArrayToBST(numLeft);
if(hasRight)
res.right = sortedArrayToBST(numRight);
return res;
}
}
}
上面提交通过,调整了一下后半段的数组,之前出现提交错误的代码如下:
/**
* 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) {
if(num == null || num.length == 0){
return null;
}else if(num.length == 1){
return new TreeNode(num[0]);
}else{
int mid = (num.length - 1) / 2;
TreeNode res = new TreeNode(num[mid]);
int[] numLeft = new int[(num.length - 1) / 2];
int[] numRight = new int[(num.length + 1) / 2];
int pivot = (num.length - 1) / 2;
for(int i = 0 ; i < num.length ; i++){
if(i < pivot){
numLeft[i] = num[i];
}else if(i > pivot){
numRight[i - pivot - 1] = num[i];
}
}
res.left = sortedArrayToBST(numLeft);
res.right = sortedArrayToBST(numRight);
return res;
}
}
}
http://jiyuede.blog.163.com/blog/static/332519212012112023814496/看了这个才懂题意,不过还是出现奇葩错误
Submission Result: Wrong Answer
Input: | [3,5,8] |
Output: | {5,3,8,#,#,#,0} |
Expected: | {5,3,8} |