Donate Us

Wednesday, March 4, 2020

Construct BST
Send Feedback

Given a sorted integer array A of size n which contains all unique elements. You need to construct a balanced BST from this input array. Return the root of constructed BST.

Note : If array size is even, take first mid as root.
Input format :
Line 1 : Integer n (Size of array)
Line 2 : Array elements (separated by space)
Output Format :
BST elements (in pre order traversal, separated by space)
Sample Input :
7
1 2 3 4 5 6 7
Sample Output :
4 2 1 3 6 5 7 


  1. public class Solution {

  2. /* Binary Tree Node class 
  3.  * 
  4.  * class BinaryTreeNode<T> {
  5. T data;
  6. BinaryTreeNode<T> left;
  7. BinaryTreeNode<T> right;
  8. public BinaryTreeNode(T data) {
  9. this.data = data;
  10. }
  11. }
  12. */
  13.     
  14.     private static BinaryTreeNode<Integer> makeBstFromSortedArray(int[] arr,int start, int end) {
  15. if(start>end)
  16. {
  17. return null;
  18. }
  19. int mid = (start+end)/2;
  20. BinaryTreeNode<Integer> root = new BinaryTreeNode<>(arr[mid]);
  21. //Now we will make left side of Bst
  22. BinaryTreeNode<Integer> left = makeBstFromSortedArray(arr,start,mid-1);
  23. //Now we will make right sider of binary search tree 
  24. BinaryTreeNode<Integer> right = makeBstFromSortedArray(arr,mid+1,end);
  25. root.left = left;
  26. root.right = right;
  27. return root;
  28. }

  29. public static BinaryTreeNode<Integer> SortedArrayToBST(int[] arr){
  30.         
  31.         int start = 0;
  32. int end = arr.length-1;
  33. return makeBstFromSortedArray(arr,start,end);
  34. }
  35. }

No comments:

Post a Comment

Popular Posts

COO Prime Naukri

COO Prime Naukri

Total Pageviews

Tags

Popular Posts