给定一个有序整数数组,元素各不相同且按升序排列,编写一个算法,创建一棵高度最小的二叉搜索树。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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) {
if (nums == null || nums.length == 0) {
return null;
}
return construct(nums, 0, nums.length - 1);
}
private TreeNode construct(int[] nums, int from, int to) {
TreeNode midNode = createMid(nums, from, to);
if (midNode == null) {
return midNode;
}
int mid = from + (to - from) / 2;
TreeNode leftN = construct(nums, from, mid - 1);
TreeNode rightN = construct(nums, mid + 1, to);
midNode.left = leftN;
midNode.right = rightN;
return midNode;
}
private TreeNode createMid(int[] nums, int from, int to) {
if (from > to) {
return null;
}
int mid = from + (to - from) / 2;
TreeNode newNode = new TreeNode(nums[mid]);
return newNode;
}
}
//leetcode submit region end(Prohibit modification and deletion)