Модтой жишээ: Энгийн
#include<stdlib.h>
#include<iostream.h>
#include<conio.h>
#include<time.h>
int i=0,d,k,el[100],n,x,y;
char ch;
class bintree { struct node { int data; node *r,*l;
node(int item) { data=item;l=r=NULL;}
};
node *root;
public:
bintree() {root=NULL;}
node *getroot() {return root;}
void insert(int d);
void print(node *p,int,int,int);
void find(int i) ;
};
void bintree::find(int i)
{node *p,*back;
p=root;
back=NULL;
while(p->data!=i)
{back=p;
if(p->data>i) p=p->l;
else p=p->r ;
}
node *temp;
if(p->r==NULL&&p->l==NULL)
if(back==NULL) root=NULL;
else if(back->r==p)
back->r=NULL;
else back->l=NULL;
else if(p->r!=NULL&&p->l!=NULL)
{ back=p;
temp=p->l;
while(temp->r!=NULL)
{ back=temp;
temp=temp->r;
}
p->data=temp->data;
if(back==p)
back->l=temp->l;
else back->r=temp->r;
p=temp;
}
else
if(p->r!=NULL)
if(back==NULL)
root=p->r;
else
if(back->r==p) back->r=p->r;
else back->l=p->l;
else
if(back==NULL)
root=p->l;
else
if(back->r==p) back->r=p->l;
else back->l=p->l;
free(p);
cout<<" ustaglaa ";
getch();
}
void bintree::insert(int d)
{ node *p=root,*b;
while(p) { b=p;
if(d<p->data) p=p->l;
else p=p->r;}
p=new node(d);
if(!root) {root=p;}
else { if(b->data>d) b->l=p;
else b->r=p;}
};
void bintree::print(node *p,int z,int x,int y)
{ if(p!=NULL) { print(p->l,z/2,x-z/2,y+1); gotoxy(x,y);
cout<<p->data<<endl;
print(p->r,z/2,x+z/2,y+2);
}
};
void menu()
{cout<<" tree tree tree tree tree tree treeee treee tree "<<endl;
cout <<" 1:nemeh 2:ustgah 3:hevleh 4:garah \n";
cout<<" tree tree tree tree tree tree treeee treee tree "<<endl;
}
void main()
{ clrscr();
bintree tree;
int i,n,m,k;
char ch;
for(;;)
{ clrscr();
menu();
cout<<endl;
ch=getch();
switch(ch){
case '1': {cout<<"too = "; cin>>m;tree.insert(m); break;}
case '2':{cout<<"ustgah too= "; cin>>n; tree.find(n);break;}
case '3':{tree.print(tree.getroot(),40,40,5); cout<<endl; getch();break;}
case '4':{tree.print(tree.getroot(),40,40,5); getch();exit(0);break;}
}
}
getch();
}
No comments:
Post a Comment