Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
基本方法就是divide and conquer
把整个数组拆分成两半,中间那个为根节点,左边为root.left,右边为root.right,最后返回root即可
基本模型还是二分查找(递归方法)的模型
代码如下
public TreeNode sortedArrayToBST(int[] num) {
if (num == null || num.length == 0)
return null;
return helper(num, 0, num.length - 1);
}
public TreeNode helper(int[] num, int left, int right) {
if (left > right)
return null;
int middle = (left + right) / 2;
TreeNode root = new TreeNode(num[middle]);
root.left = helper(num, left, middle - 1);
root.right = helper(num, middle + 1, right);
return root;
}