#include<iostream>
#include<queue>
using namespace std;
struct tree
{
int num;
tree *left,*right;
}*root;
void levelOrder(tree *r)
{
queue <tree*> q;
q.push(r);
while(!q.empty())
{
tree *d =q.front();
q.pop();
cout<<d->num<<" ";
if(d->left) q.push(d->left);
if(d->right) q.push(d->right);
}
}
tree * create(int n)
{
tree *t = new tree;
t->left=t->right=NULL;
t->num=n;
return t;
}
tree * add(tree *r,int n)
{
if(r==NULL)
{
r=create(n);
}
else if(r->num>n)
{
r->right=add(r->right,n);
}
else
r->left=add(r->left,n);
return r;
}
void display(tree * t)
{
if(t==NULL)
{
return ;
}
else
{
cout<<t->num<<" ";
display(t->left);
display(t->right);
}
}
int main()
{
root =NULL;
int n,t;
while(true)
{
cout<<"Enter 1 for add Enter 2 for diplay "<<endl;
cin>>n;
switch(n)
{
case 1:
cout<<"Enter the number "<<endl;
cin>>t;
root=add(root,t);
break;
case 2:
display(root);
break;
case 3:
levelOrder(root);
break;
}
}}
No comments:
Post a Comment