题目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
方法
数组是有序的,要求创建的二叉树尽量平衡,很容易想到对数组进行二分操作,左边的数组元素是左子树,右边的数组元素是右子树。进行递归操作就可以了。
TreeNode getBST(int[] num, int start , int end) {
if (start >= end) {
return null;
}
int median = (start + end) / 2;
int value = num[median];
TreeNode root = new TreeNode(value);
root.left = getBST(num, start, median);
root.right = getBST(num, median + 1, end);
return root;
}
public TreeNode sortedArrayToBST(int[] num) {
if (num == null || num.length == 0) {
return null;
}
int len = num.length;
return getBST(num, 0, len);
}