示例 示例 1:
输入:nums = [-10,-3,0,5,9]
输出:[0,-3,9,-10,null,5]
解释:[0,-10,5,null,-3,null,9] 也将被视为正确答案:
示例 2:
输入:nums = [1,3]
输出:[3,1]
解释:[1,null,3] 和 [3,1] 都是高度平衡二叉搜索树。
代码(Java) class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null) {
return null;
}
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
return sortedArrayToBST(nums, 0, nums.length - 1, (nums.length - 1) / 2);
}
public TreeNode sortedArrayToBST(int[] nums, int left, int right, int mid) {
if (left > right) {
return null;
}
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, left, mid - 1, (left + mid - 1) / 2);
root.right = sortedArrayToBST(nums, mid + 1, right, (mid + 1 + right) / 2);
return root;
}
}