题目
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析
数组元素可以直接定位,比Convert Sorted List to Binary Search Tree要好写点。
代码
public class ConvertSortedArrayToBinarySearchTree {
public TreeNode sortedArrayToBST(int[] num) {
if (num == null || num.length == 0) {
return null;
}
int N = num.length;
return solve(num, 0, N - 1);
}
private TreeNode solve(int[] num, int low, int high) {
if (low > high) {
return null;
}
int mid = low + (high - low) / 2;
TreeNode root = new TreeNode(num[mid]);
root.left = solve(num, low, mid - 1);
root.right = solve(num, mid + 1, high);
return root;
}
}