题目:
题解:
代码:
/** * code108 */
public class code108 {
// 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
public static TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
return sort(nums, 0, nums.length - 1);
}
public static TreeNode sort(int nums[], int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sort(nums, start, mid - 1);
root.right = sort(nums, mid + 1, end);
return root;
}
public static void main(String[] args) {
int nums[] = { -10, -3, 0, 5, 9 };
TreeNode tree = sortedArrayToBST(nums);
TreeOperation.show(tree);
}
}