二分法构造AVL树

public class ConvertSortedArrayToBinarySearchTree {
    public static TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return buildFromSorted(0, nums.length - 1, nums);
    }

    public static TreeNode buildFromSorted(int lo, int hi, int[] nums) {
        if (hi < lo)
            return null;
        int mid = (lo + hi) / 2; //3个相等,就只有mid没有左右节点。

        TreeNode left = null;
        if (lo < mid)//lo只能小于等于mid。只有2个元素时候lo=mid,hi=mid+1=lo+1。
            //就有根节点mid,没有左节点,有右节点hi=mid+1。
            left = buildFromSorted(lo, mid - 1, nums);
        TreeNode middle = new TreeNode(nums[mid]);
        if (left != null) {
            middle.left = left;
        }
        if (mid < hi) {
            TreeNode right = buildFromSorted(mid + 1, hi, nums);
            middle.right = right;
        }
        return middle;//middle是根,left是左节点,right是右节点。
    }
    
    public static void main(String[] args) {
        TreeNode tn = sortedArrayToBST(new int[] {1,2,3,4,5,6,7,8,9,10,11,12});
    }
}
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) {
        val = x;
    }
    public TreeNode(int val, TreeNode left, TreeNode right) {
        super();
        this.val = val;
        this.left = left;
        this.right = right;
    }
    public TreeNode() {
        super();
    }
}

 

posted @ 2019-07-02 16:30  无天666  阅读(387)  评论(0编辑  收藏  举报