题目描述:
给你一个整数数组 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] 都是高度平衡二叉搜索树。
代码思路:
/**
* 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.length==0){
return null;
}
TreeNode root = new TreeNode();
locat(root , 0, nums.length-1,nums);
return root;
}
public void locat(TreeNode root,int low,int high,int[] nums){
int mid = (low+high)/2;
root.val = nums[mid];
if(low<mid){
TreeNode lx = new TreeNode();
root.left = lx;
locat(lx,low,mid-1,nums);
}
if(mid<high){
TreeNode rx = new TreeNode();
root.right = rx;
locat(rx,mid+1,high,nums);
}
}
}