LeetCode:108 将有序数组转换为二叉搜索树

class Solution {

    public TreeNode Build(int[]nums,int left,int right){
        if(left>right){
            return null;
        }
        int mid = (left+right)>>1;
        TreeNode t = new TreeNode(nums[mid]);
        t.left = Build(nums,left,mid-1);
        t.right = Build(nums,mid+1,right);
        return t;
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0){
            return null;
        }
        int r = nums.length/2;
        int len = nums.length-1;
        TreeNode root = new TreeNode(nums[r]);
        root.left = Build(nums,0,r-1);
        root.right = Build(nums,r+1,len);
        return root;
    }
}

 

posted @ 2020-10-09 09:55  dlooooo  阅读(102)  评论(0编辑  收藏  举报