Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题解:递归就可以了。
Java代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return Helper(num, 0, num.length-1);
}
public TreeNode Helper(int[] num,int begin,int end){
if(begin > end)
return null; int mid = (begin + end)/2;
TreeNode root = new TreeNode(num[mid]);
root.left = Helper(num, begin, mid-1);
root.right = Helper(num, mid+1, end);
return root;
}
}