Write a program to get the binary tree.

Answer Posted / vamshi koduri

#include<iostream>
using namespace std;
typedef struct node
{
int d;
struct node *l,*r;
}node;
class bt
{
public:
int h,lev;
node *root;
node *create();
int height(node *);
void printlevel(node *,int lev);
void givenlevel();
void inorder(node *);
void preorder(node *);
void postorder(node *);
}a;
node *bt::create()
{
struct node *n;
n=new node;
int x;
cout<<"enter element
";
cin>>x;
if(x==-1)
return NULL;
n->d=x;
n->l=n->r=NULL;
cout<<"enter left "<<n->d<<ends;
n->l=create();
cout<<"enter right "<<n->d<<ends;
n->r=create();
return n;
}
void bt::inorder(node *p)
{
if(p!=NULL)
{
inorder(p->l);
cout<<p->d<<ends;
inorder(p->r);
}
}
void bt::preorder(node *q)
{
if(q!=NULL)
{
cout<<q->d<<ends;
preorder(q->l);
preorder(q->r);
}
}
void bt::postorder(node *q)
{
if(q!=NULL)
{
postorder(q->l);
postorder(q->r);
cout<<q->d<<ends;
}
}
int main()
{
a.root=a.create();
cout<<"levelorder: ";
a.givenlevel();
cout<<endl;
cout<<"inorder : ";
a.inorder(a.root);
cout<<endl;
cout<<"preorder : ";
a.preorder(a.root);
cout<<endl;
cout<<"postorder : ";
a.postorder(a.root);
cout<<endl<<"height: ";
cout<<a.height(a.root);
return 0;
}
int bt::height(node *p)
{
if(p==NULL)
return 0;
int l=height(p->l);
int r=height(p->r);
if(l>r)
h=1+l;
else
h=1+r;
return h;
}
void bt::givenlevel()
{
int p=height(root);
for(int i=1;i<=h;i++)
printlevel(root,i);
}
void bt::printlevel(node *p,int lev)
{
if(p==NULL)
return;
if(lev==1)
cout<<p->d<<ends;
if(lev>1)
{
printlevel(p->l,lev-1);
printlevel(p->r,lev-1);
}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the oops and benefits of oops programming?

549


What is the difference between abstraction and polymorphism?

609


What is inheritance in simple words?

623


What is polymorphism oop?

615


class type to basic type conversion

1833






What are the 4 main oop principles?

675


What is overloading in oops?

596


Is oop better than procedural?

563


What is polymorphism in oop example?

512


What is polymorphism and its types?

589


What is interface in oop?

656


What is a function in oop?

627


How long to learn object oriented programming?

559


program for insertion ,deletion,sorting in double link list

2276


What is class and example?

565