Friday, August 31, 2012

C++ program for Binary Search Tress (BST)

#include<iostream.h>
#include<alloc.h>
#include<conio.h>
struct tree
{
       int value;
       struct tree *right,*left;
};
void create(struct tree *h,struct tree *q)
{
   if(q->value>h->value)
   {
     if(h->right!=NULL)
     create(h->right,q);
     else
     h->right=q;
   }
   else//(q->value>h-value)
   {
     if(h->left!=NULL)
     create(h->left,q);
     else
     h->left=q;
   }

}
void BST(tree *h)
{
 cout<<"Enter Value";
 struct tree *q;
 q=(tree*)malloc(sizeof(tree));
 cin>>q->value;
 q->right=NULL;
 q->left=NULL;
 create(h,q);
 cout<<"Continue Y/N";
 if(getch()=='y')
 BST(h);
 else
 return;
}
void print_inorder(struct tree *p)
{
     if(p==NULL)return;
     print_inorder(p->left);
     cout<<endl<<p->value;
     print_inorder(p->right);
}
void main()
{
     clrscr();
     struct tree *a;
     a=(tree*)malloc(sizeof(tree));
     cout<<"Enter Tree\n";
     BST(a);
//     cout<<"\n Preorder\n";
     //print_preorder(a);
     cout<<"\n Inorder\n";
     print_inorder(a);
//     cout<<"\n Postorder\n";
  ///   print_postorder(a);
     getch();
}

No comments:

Post a Comment