Trees in C++

Implementation of Binary Tree .... 
In-Order Traversal
Pre-Order Traversal
Post-Order Traversal



#include<iostream.h>
#include<conio.h>
class treenode{
public:
int info;
treenode *left,*right;
treenode()
{ this->info=NULL;
  this->left=NULL;
  this->right=NULL;
}
treenode(int info)
{ this->info=info;
  this->left=NULL;
  this->right=NULL;
}
void setinfo(int info)
{ this->info=info; }
int getinfo()
{ return info; }
void setleft(treenode *left)
{  this->left=left; }
void setright(treenode *right)
{   this->right=right; }
treenode *getleft()
{ return left; }
treenode *getright()
{  return right; }

void insert(treenode *root,int info)
{
treenode *node=new treenode(info);
treenode *p,*q;
p=q=root;
while(info!=p->getinfo() && q!=NULL)
{
p=q;
if(info<p->getinfo())
{ q=p->getleft(); }
else
{  q=p->getright(); }
}
if(info==p->getinfo())
{ cout<<" \n Attempt to insert duplicate "<<info<<endl;
delete node;
}
else if(info<p->getinfo())
{ p->setleft(node); }
else
{p->setright(node); }
}

void preorder(treenode *root)
{
if(root!=NULL)
{ cout<<"\t"<<root->getinfo();
preorder(root->getleft());
preorder(root->getright());
}}
void postorder(treenode *root)
{
if(root!=NULL)
{
postorder(root->getleft());
postorder(root->getright());
cout<<"\t"<<root->getinfo();
}}
void inorder(treenode *root)
{
if(root!=NULL)
{
inorder(root->getleft());
cout<<"\t"<<root->getinfo();
inorder(root->getright());
}}
};
void main()
{
clrscr();
int x[]={14,15,4,8,7,3,5,2,1,9,6,-1};
treenode *root=new treenode();
root->setinfo(x[0]);
for(int i=1;x[i]>0;i++)
{ root->insert(root,x[i]);}
cout<<"\n\nDispaly ::Pre Order\n\n";
root->preorder(root);
cout<<"\n\n Display ::In Order\n\n";
root->inorder(root);
cout<<"\n\n Display ::Post Order\n\n";
root->postorder(root);
getch();

}


3 comments

Anonymous said...

Enter tuition fee: 20000
Enter the mode of payment:
A:cash. 20%discount
B:two installment.10%discount
C:three installment 1%discount
Turbo c DOSBox

Anonymous said...

thankx :)

Anonymous said...

Comment

Powered by Blogger.