public class SortedArrayToBST {
BTNode BSTRoot;
public static void main(String[] args) {
SortedArrayToBST application = new SortedArrayToBST();
int[] nums = { -10, -3, 0, 5, 9 };
application.BSTRoot = application.convertArrayToBST(nums);
System.out.println(application.BSTRoot.val);
System.out.println(application.BSTRoot.left.val);
System.out.println(application.BSTRoot.left.right.val);
System.out.println(application.BSTRoot.right.val);
System.out.println(application.BSTRoot.right.right.val);
}
public BTNode convertArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
return constructBST(nums, 0, nums.length - 1);
}
private BTNode constructBST(int[] nums, int left, int right) {
if (left > right)
return null;
int middle = left + (right - left) / 2;
BTNode currentNode = new BTNode(nums[middle], null, null);
currentNode.left = constructBST(nums, left, middle - 1);
currentNode.right = constructBST(nums, middle + 1, right);
return currentNode;
}
private class BTNode {
int val;
BTNode left;
BTNode right;
public BTNode(int val, BTNode left, BTNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}