Convert Sorted Array to Binary Search Tree

/**
 * 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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值