给你一个整数数组 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;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null && nums.length == 0) {
return null;
}
int middle = nums.length / 2;
int[] numsLeft = Arrays.copyOf(nums, middle);
int[] numsRight = Arrays.copyOfRange(nums, middle + 1, nums.length);
TreeNode treeNode = new TreeNode(nums[middle]);
sortedArrayToBST(numsLeft, numsRight, treeNode);
return treeNode;
}
public void sortedArrayToBST(int[] numsLeft, int[] numsRight, TreeNode treeNode) {
if (numsLeft != null && numsLeft.length > 0) {
int middleLeft = numsLeft.length / 2;
int[] numsLeftTemp = Arrays.copyOf(numsLeft, middleLeft);
int[] numsRightTemp = Arrays.copyOfRange(numsLeft, middleLeft + 1, numsLeft.length);
treeNode.left = new TreeNode(numsLeft[middleLeft]);
sortedArrayToBST(numsLeftTemp, numsRightTemp, treeNode.left);
}
if (numsRight != null && numsRight.length > 0) {
int middleRight = numsRight.length / 2;
int[] numsLeftTemp = Arrays.copyOf(numsRight, middleRight);
int[] numsRightTemp = Arrays.copyOfRange(numsRight, middleRight + 1, numsRight.length);
treeNode.right = new TreeNode(numsRight[middleRight]);
sortedArrayToBST(numsLeftTemp, numsRightTemp, treeNode.right);
}
}
}
标签:TreeNode,数组,nums,int,length,二叉,numsRight,numsLeft,有序
From: https://blog.csdn.net/linsa_pursuer/article/details/143139506