#include<iostream>
#include<cmath>
#include<queue>
using namespace std;
struct tree
{
int num;
tree* left,*right;
}*root;
tree * create(int n)
{
tree *t= new tree;
t->num=n;
t->left=t->right=NULL;
return t;
}
tree * add(tree * r,int nu)
{
if(r==NULL)
{
r= create(nu);
}
else if(nu<=r->num)
{
r->left= add(r->left,nu);
}
else
r->right=add(r->right,nu);
return r;
}
void disply(tree * t)
{
if(t==NULL)
{
return;
}
else
{
cout<<t->num<<" ";
disply(t->left);
disply(t->right);
}
}
tree * deletes(tree * t)
{
while(t->left!=NULL)
{
t=t->left;
}return t;
}
tree * deleteNode(tree * r,int d)
{
if(r==NULL)
{
return r;
}
else if(d<r->num)
{
r->left=deleteNode(r->left,d);
}
else if(d>r->num)
{
r->right=deleteNode(r->right,d);
}
else {
if(r->left==NULL&&r->right==NULL)
{
delete r;
r=NULL;
}
else if(r->right==NULL)
{
tree * temp;
temp=r;
r=r->left;
delete temp;
}
else if(r->left==NULL)
{
tree * temp;
temp=r;
r=r->right;
delete temp;
}
else
{
tree *temp=deletes(r->right);
r->num=temp->num;
r->right=deleteNode(temp,temp->num);
}
}
return r;
}
void printLevelOrder(tree *root) {
if (!root) return;
queue<tree*> nodesQueue;
int nodesInCurrentLevel = 1;
int nodesInNextLevel = 0;
nodesQueue.push(root);
while (!nodesQueue.empty()) {
tree *currNode = nodesQueue.front();
nodesQueue.pop();
nodesInCurrentLevel--;
if (currNode) {
cout << currNode->num << " ";
nodesQueue.push(currNode->left);
nodesQueue.push(currNode->right);
nodesInNextLevel += 2;
}
if (nodesInCurrentLevel == 0) {
cout <<endl;
nodesInCurrentLevel = nodesInNextLevel;
nodesInNextLevel = 0;
}
}
}
void CMI(tree *r)
{
tree*temp,*temp1;
temp=r->left;
r->left=r->right;
r->right=temp;
}
int main()
{
root==NULL;
int n,a,m=1;
while(1){
cout<<"Enter 1 for add\n Enter 2 for display\n Enter 3 for delete node\n Enter 4 for createMirrorImage"<<endl;
cin>>n;
switch(n)
{
case 1:
cout<<"Enter the number for add"<<endl;
cin>>a;
root=add(root,a);
break;
case 2:
printLevelOrder(root);
break;
case 3:
cout<<"Enter the number for delete"<<endl;
cin>>a;
root=deleteNode(root,a);
break;
case 4:
CMI(root);
printLevelOrder(root);
break;
}
}
}
No comments:
Post a Comment