Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Pick the middle element of the array as a head node, use recursion to set the left and right nodes.
/**
* 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) {
if (num == null) {
return null;
}
return buildBST(num, 0, num.length - 1);
}
private TreeNode buildBST(int[] num, int start, int end) {
if (start > end) {
return null;
}
TreeNode node = new TreeNode(num[(start + end) / 2]);
node.left = buildBST(num, start, (start + end) / 2 - 1);
node.right = buildBST(num, (start + end) / 2 + 1, end);
return node;
}
}