给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵平衡二叉搜索树。
示例 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] 都是高度平衡二叉搜索树。
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 按 严格递增 顺序排列
我第一个方案是采用的数组截取的方式
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.Arrays;
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null)
return null;
int mid = (nums.length) / 2;
TreeNode root = new TreeNode(nums[mid]);
// left 0,mid-1,right mid+1,nums.lenght-1
if (mid == 1) {
root.left = new TreeNode(nums[0]);
} else if (mid >= 2) {
int[] leftnums = Arrays.copyOfRange(nums, 0, mid);
root.left = sortedArrayToBST(leftnums);
}
if (mid == nums.length - 2) {
root.right = new TreeNode(nums[nums.length - 1]);
} else if (mid < nums.length - 2) {
int[] rightnum = Arrays.copyOfRange(nums, mid + 1, nums.length);
root.right = sortedArrayToBST(rightnum);
}
return root;
}
}
这个方案AI优化后,认为可以通过索引的方式完成递归,以下为优化后的代码
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
return buildBST(nums, 0, nums.length - 1);
}
private TreeNode buildBST(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 = buildBST(nums, start, mid - 1);
root.right = buildBST(nums, mid + 1, end);
return root;
}
}