Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
int n=num.length;
if(num==null||n==0){
return null;
}
return createBst(num,0,n-1);
}
public static TreeNode createBst(int num[],int start,int end){
if(start>end){
return null;
} int mid=(start+end+1)/2;
TreeNode root=new TreeNode(num[mid]);
root.left=createBst(num,start,mid-1);
root.right=createBst(num,mid+1,end);
return root;
}
}
Recursion method is noted that when the intermediate node seeking start + end + 1; note boundary conditions.