Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.


一个变形的对数组的二分搜索

/**
 * 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;
        }
        int mid = num.length/2;
        TreeNode root = new TreeNode(num[mid]);
        sortedArrayToBST(num,0,mid-1,root);
        sortedArrayToBST(num,mid+1,num.length-1,root);
        return root;
    }
    public void sortedArrayToBST(int[] num,int start,int end,TreeNode root) {
        if(start>end){
            return;
        }
        int mid = (start+end)/2;
        TreeNode node = new TreeNode(num[mid]);
        if(num[mid]>=root.val){
            root.right = node;
        }else{
            root.left = node;
        }
        sortedArrayToBST(num,start,mid-1,node);
        sortedArrayToBST(num,mid+1,end,node);
    }
}

你可能感兴趣的:(java,LeetCode)