Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
解题思路:就是用2分查找的方案,然后进行深度搜索的方案,递归将数组转化成二分查找数。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
int len = nums.length -1;
if(len == -1)
return null;
return sortedArrayToBST(nums, 0, len);
}
private TreeNode sortedArrayToBST(int[] nums, int start, int end){
if(start > end)
return null;
int mid = (end+start)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, start, mid-1);
root.right = sortedArrayToBST(nums, mid+1, end);
return root;
}
}