http://www.lintcode.com/en/problem/convert-sorted-array-to-binary-search-tree-with-minimal-height/
since the array is sorted. to ensure the minimum depth. we need to make sure that the number of nodes in left as equal to the number of nodes in right as possible. so we get a mid and create node use that and recursively going to the left and right.
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param A: an integer array
* @return: a tree node
*/
public TreeNode sortedArrayToBST(int[] A) {
// write your code here
if (A == null || A.length == 0) {
return null;
}
return helper(A, 0, A.length - 1);
}
public TreeNode helper(int[] A, int start, int end) {
if (start == end) {
return new TreeNode(A[start]);
}
if (start > end) {
return null;
}
int mid = (start + end) / 2;
TreeNode newRoot = new TreeNode(A[mid]);
newRoot.left = helper(A, start, mid - 1);
newRoot.right = helper(A, mid + 1, end);
return newRoot;
}
}