Sunday, February 2, 2014

Given a sorted array, convert it into a balanced binary search tree

#include<iostream>
using namespace std;

struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* createnode(int x)
{
struct node* new_node=new struct node;
new_node->data=x;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
int height(struct node* root)
{
if(root==NULL)
{
return 0;
}
else
{
int lheight=1+height(root->left);
int rheight=1+height(root->right);
return lheight>rheight?lheight:rheight;
}
}
struct node* createBST(int *A, int low, int high)
{
if(low>high)
{
return NULL;
}
else
{
int mid = (low + high)/2;
struct node* root = createnode(A[mid]);
root->left = createBST(A, low, mid - 1);
root->right = createBST(A, mid + 1, high);
return root;
}
}
void levelorderprint(struct node* root,int level)
{
if(root && level==0)
{
cout<<root->data<<" ";
}
else if(root)
{
levelorderprint(root->left,level-1);
levelorderprint(root->right,level-1);
}
}
void levelorder(struct node* root)
{
int h=height(root);
for(int i=0;i<h;i++)
{
levelorderprint(root,i);
cout<<endl;
}
}
int main()
{
int A[6] = {1,2,3,4,5,6};
int n = 5;
struct node* treeRoot = createBST(A,0,n-1);
levelorder(treeRoot);
}

No comments:

Post a Comment