题目链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
最好的方法就是有序数组中间的数作为每个子树的根,然后左边的数作为左子树,右边的数作为右子树,这样使用递归就可求出该平衡树。
不要被高度差绝对值不超过1所迷惑,其实按照上述方法构造,高度差不会超过1的。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return nums == null ? null : highBalanceBinTree(nums, 0, nums.length - 1);
}
public TreeNode highBalanceBinTree(int[] nums, int left, int right){
if (left > right){
return null;
}
int mid = left + ((right - left) >> 1);
TreeNode root = new TreeNode(nums[mid]);
root.left = highBalanceBinTree(nums, left, mid - 1);
root.right = highBalanceBinTree(nums, mid + 1, right);
return root;
}
}