[leedcode 108] Convert Sorted Array to Binary Search Tree
2259 ワード
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// , , start end, start end
// ,
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null||nums.length==0) return null;
return getBST(nums,0,nums.length-1);
}
TreeNode getBST(int[] nums,int start,int end){
if(start>end) return null;
int mid=(start+end)/2;
TreeNode node=new TreeNode(nums[mid]);
node.left=getBST(nums,start,mid-1);
node.right=getBST(nums,mid+1,end);
return node;
}
}