|
| 1 | +/* |
| 2 | +Given a sorted (increasing order) array, Convert it to create a binary tree with minimal height. |
| 3 | +
|
| 4 | +Have you met this question in a real interview? Yes |
| 5 | +Example |
| 6 | +Given [1,2,3,4,5,6,7], return |
| 7 | +
|
| 8 | + 4 |
| 9 | + / \ |
| 10 | + 2 6 |
| 11 | + / \ / \ |
| 12 | +1 3 5 7 |
| 13 | +Note |
| 14 | +There may exist multiple valid solutions, return any of them. |
| 15 | +
|
| 16 | +Tags Expand |
| 17 | +Cracking The Coding Interview Recursion Binary Tree |
| 18 | +
|
| 19 | +Thoughts: |
| 20 | +1. Find middle point x. |
| 21 | +2. All index before x, goes to left of the tree. Same apply to right tree |
| 22 | + build sub array and pass alone: we can pass index start, end. |
| 23 | + use parent node and pass along |
| 24 | +3. Recur on left side array. |
| 25 | +
|
| 26 | +*/ |
| 27 | + |
| 28 | + |
| 29 | +/** |
| 30 | + * Definition of TreeNode: |
| 31 | + * public class TreeNode { |
| 32 | + * public int val; |
| 33 | + * public TreeNode left, right; |
| 34 | + * public TreeNode(int val) { |
| 35 | + * this.val = val; |
| 36 | + * this.left = this.right = null; |
| 37 | + * } |
| 38 | + * } |
| 39 | + */ |
| 40 | +public class Solution { |
| 41 | + /** |
| 42 | + * @param A: an integer array |
| 43 | + * @return: a tree node |
| 44 | + */ |
| 45 | + public TreeNode sortedArrayToBST(int[] A) { |
| 46 | + TreeNode root = null; |
| 47 | + if (A == null || A.length == 0) { |
| 48 | + return root; |
| 49 | + } |
| 50 | + root = helper(0, A.length - 1, A); |
| 51 | + return root; |
| 52 | + } |
| 53 | + |
| 54 | + public TreeNode helper(int start, int end, int[] A) { |
| 55 | + if (start > end) { |
| 56 | + return null; |
| 57 | + } |
| 58 | + //add middle node |
| 59 | + int mid = start + (end - start)/2; |
| 60 | + TreeNode node = new TreeNode(A[mid]); |
| 61 | + //Split and append child |
| 62 | + node.left = helper(start, mid - 1, A); |
| 63 | + node.right = helper(mid + 1, end, A); |
| 64 | + return node; |
| 65 | + } |
| 66 | +} |
0 commit comments