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
本题题意其实就是二分查找
代码,如下:
/**
* 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) {
return buildBST(0, nums.length-1, nums);
}
public TreeNode buildBST(int low, int high, int[] nums){
if(low > high){
return null;
}
int mid = (low + high) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = buildBST(low, mid - 1, nums);
root.right = buildBST(mid + 1, high, nums);
return root;
}
}