将已排好序的数组转换成高度平衡的二叉搜索树(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;
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/sunzz_pku/article/details/44160457
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞