Sorted Array to Balanced BST
PROBLEM :
Given a sorted array. Write a program that creates a Balanced Binary Search Tree using array elements. If there are n elements in array, then floor(n/2)'th element should be chosen as root and same should be followed recursively.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input A[].
Output:
Print the preorder traversal of constructed BST.
Constraints:
1 = T = 100
1 = N = 1000
1 = A[] = 10000
Example:
Input:
1
7
7 6 5 4 3 2 1
Output:
4 6 7 5 2 3 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void preorder_tree(int [],int ,int ) ;
int main()
{
int t,no,a[1000],i ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
preorder_tree(a,0,no-1) ;
cout<<endl ;
}
return 0;
}
void preorder_tree(int a[],int start,int end)
{
if(start>end)
return ;
if(start==end)
{
cout<<a[start]<<" " ;
return ;
}
int no=(start+end)/2 ;
cout<<a[no]<<" " ;
preorder_tree(a,start,no-1) ;
preorder_tree(a,no+1,end) ;
}
---------------------------------------------------------------------------------
Given a sorted array. Write a program that creates a Balanced Binary Search Tree using array elements. If there are n elements in array, then floor(n/2)'th element should be chosen as root and same should be followed recursively.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input A[].
Output:
Print the preorder traversal of constructed BST.
Constraints:
1 = T = 100
1 = N = 1000
1 = A[] = 10000
Example:
Input:
1
7
7 6 5 4 3 2 1
Output:
4 6 7 5 2 3 1
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void preorder_tree(int [],int ,int ) ;
int main()
{
int t,no,a[1000],i ;
cin>>t ;
while(t--)
{
cin>>no ;
for(i=0;i<no;i++)
cin>>a[i] ;
preorder_tree(a,0,no-1) ;
cout<<endl ;
}
return 0;
}
void preorder_tree(int a[],int start,int end)
{
if(start>end)
return ;
if(start==end)
{
cout<<a[start]<<" " ;
return ;
}
int no=(start+end)/2 ;
cout<<a[no]<<" " ;
preorder_tree(a,start,no-1) ;
preorder_tree(a,no+1,end) ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment