Saturday, January 30, 2016

Sorted Array to Balanced BST

Question: Given a sorted array. Write a function that creates a Balanced Binary Search Tree using array elements.
Examples:
Input:  Array {1, 2, 3}
Output: A Balanced BST
     2
   /  \
  1    3 

Input: Array {1, 2, 3, 4}
Output: A Balanced BST
      3
    /  \
   2    4
 /
1
Algo:

1) Get the Middle of the array and make it root.
2) Recursively do same for left half and right half.
   a) Get the middle of left half and make it left child of root
          created in step 1.
   b) Get the middle of right half and make it right child of the           root created in step 1.
 Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Public TreeNode sortedArrayToBalancedBST(int[] a, int left, int right) {
   
  if(left>right) {
     return NULL;
  }
    
   int mid = left + (right-left)/2;
   // Create a root node with mid element
   TreeNode root = new TreeNode(a[mid]);
 
   // Recursively construct left subtree and make it as root left node
  root.left = sortedArrayToBalancedBST(a, left, mid-1);
 
  // Recursively construct right subtree and make it as root right node
  root.right = sortedArrayToBalancedBST(a, mid+1, right);
 
 return root;
}  

No comments:

Post a Comment