1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class SortedArrayToBST { public TreeNode sortedArrayToBST(int[] num) { if (num.length < 1) { return null; } if (num.length == 1) { return new TreeNode(num[0]); } return helper(0, num.length - 1, num); } private TreeNode helper(int start, int end, int[] num) { if (start <= end) { int middle = (start + end) / 2; TreeNode tree = new TreeNode(num[middle]); tree.left = helper(start, middle - 1, num); tree.right = helper(middle + 1, end, num); return tree; } else { return null; } } }
|