Sorted Array to Balanced BST - GeeksforGeeks
Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements.
http://www.ideserve.co.in/learn/create-a-balanced-bst-from-a-sorted-array
Read full article from Sorted Array to Balanced BST - GeeksforGeeks
Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements.
struct TNode* sortedArrayToBST(int arr[], int start, int end){ /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; struct TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid-1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid+1, end); return root;}| 9 | public static TreeNode createBST(int array[]) { |
| 10 | |
| 11 | return createBST(array, 0, array.length-1); |
| 12 | } |
| 13 | |
| 14 | private static TreeNode createBST(int[] array, int start, int end) { |
| 15 | |
| 16 | if(array == null || array.length == 0 || start > end) { |
| 17 | return null; |
| 18 | } |
| 19 | |
| 20 | int mid = (start + end)/2; |
| 21 | TreeNode root = new TreeNode(array[mid]); |
| 22 | |
| 23 | root.setLeft(createBST(array, start, mid-1)); |
| 24 | root.setRight(createBST(array, mid+1, end)); |
| 25 | |
| 26 | return root; |
| 27 | } |