108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
找割点,一步一步将原数组分开。妙极了!!!!!
/**
* 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;
int mid = nums.length/2;
TreeNode t = new TreeNode(nums[mid]);
t.left = sortedArrayToBST(Arrays.copyOfRange(nums,0,mid));
t.right =sortedArrayToBST(Arrays.copyOfRange(nums,mid+1,nums.length));
return t;
}
}