|
| 1 | +package DataStructures.Trees; |
| 2 | + |
| 3 | +import DataStructures.Trees.BinaryTree.Node; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given a sorted array. Create a balanced binary search tree from it. |
| 7 | + * |
| 8 | + * Steps: |
| 9 | + * 1. Find the middle element of array. This will act as root |
| 10 | + * 2. Use the left half recursively to create left subtree |
| 11 | + * 3. Use the right half recursively to create right subtree |
| 12 | + */ |
| 13 | +public class CreateBSTFromSortedArray { |
| 14 | + |
| 15 | + public static void main(String[] args) { |
| 16 | + test(new int[]{}); |
| 17 | + test(new int[]{1, 2, 3}); |
| 18 | + test(new int[]{1, 2, 3, 4, 5}); |
| 19 | + test(new int[]{1, 2, 3, 4, 5, 6, 7}); |
| 20 | + } |
| 21 | + |
| 22 | + private static void test(int[] array) { |
| 23 | + BinaryTree root = new BinaryTree(createBst(array, 0, array.length - 1)); |
| 24 | + System.out.println("\n\nPreorder Traversal: "); |
| 25 | + root.preOrder(root.getRoot()); |
| 26 | + System.out.println("\nInorder Traversal: "); |
| 27 | + root.inOrder(root.getRoot()); |
| 28 | + System.out.println("\nPostOrder Traversal: "); |
| 29 | + root.postOrder(root.getRoot()); |
| 30 | + } |
| 31 | + |
| 32 | + private static Node createBst(int[] array, int start, int end) { |
| 33 | + // No element left. |
| 34 | + if (start > end) { |
| 35 | + return null; |
| 36 | + } |
| 37 | + int mid = start + (end - start) / 2; |
| 38 | + |
| 39 | + // middle element will be the root |
| 40 | + Node root = new Node(array[mid]); |
| 41 | + root.left = createBst(array, start, mid - 1); |
| 42 | + root.right = createBst(array, mid + 1, end); |
| 43 | + return root; |
| 44 | + } |
| 45 | +} |
0 commit comments