Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height.
There is a same problem on leetcode, https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/. The idea is similar to binary search, since each time, it divide the array into two parts with similar number of elements.
/*In order to make the tree as balance as possible, we hope the left subtree and right subtree have as much as number of nodes, this would turn the problem to find the middle of the array. Use the middle as a root, and use left array to create another tree and right ones the right subtree using the same process. Then the tree would have balanced height, as well as the minimum height.*/ public class ArrayToBalancedBST { public TreeNode sortedArrayToBST(int[] num) { int len = num.length; return helper(num, 0, len-1); } private TreeNode helper(int[] num, int l, int h) { if(l > h) return null; else { int mid = (l + h) / 2; TreeNode node = new TreeNode(num[mid]); node.left = helper(num, l, mid-1); node.right = helper(num, mid+1, h); return node; } } }