将已排好序的数组转换成高度平衡的二叉搜索树(BST)

题目要求:给定一个数组,元素已经按照升序排列,将其转换成高度平衡的二叉搜索树(BST)

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public TreeNode sortedArrayToBST(int[] num) {
	int len = num.length;

    if (num.length == 0) {	//异常判断
        return null;
    }

    return recurseOpera(num, 0, len - 1);
}
//因为数组已经排好序
//所以每次只需要取出数组的中间位的数据来生成一个节点,然后递归即可
public TreeNode recurseOpera(int[] num, int low, int high) {
    if (low > high) { 	//递归的出口
        return null;
    }
    int mid = (low + high) / 2;
    TreeNode tnode = new TreeNode(num[mid]);
    tnode.left = recurseOpera(num, low, mid - 1);
    tnode.right = recurseOpera(num, mid + 1, high);

    return tnode;
}



你可能感兴趣的:(算法)