səhifə 9/9 tarix 18.12.2023 ölçüsü 108,47 Kb. #184135
binar daraxt
p tugun otasi q tugunning qaysi tomonida turgan edi? Agar p q ning chapida turgan bo‘lsa, p ning o‘rniga, ya’ni q->left ga v ni joylaymiz, aks holda q->right ga v ni joylaymiz.
p tugun joylashgan xotira yacheykasini tozalab qo‘yamiz va algoritm yakunlanadi.
Dastur kodi
#include
#include
using namespace std;
class node{
public: int info;
node *left;
node *right;
};
int intrave(node *tree){
if (tree!=NULL){int a=0, b=0;
if (tree->left!=NULL){ a=tree->left->info; }
if (tree->right!=NULL){ b=tree->right->info; }
cout<info<<"--chapida=>"<"<
intrave(tree->left);
intrave(tree->right); }
return 0;
}
node *del(node *tree,int key){
node *p=new node;
node *next=tree;
node *q=NULL;
while(next!=NULL)
{ if (next->info==key){cout<<"Binar daraxtda "<
p=next;break; }
if (next->info>key){ q=next; next=next->left; }
else {q=next;next=next->right;}
}
if(next==NULL) cout<<"tuzilmada izlangan element yo‘q!!!"<
node *v=NULL,*t=NULL,*s=NULL;
if(p->left==NULL) v=p->right;
else if(p->right==NULL) v=p->left;
if((p->left!=NULL)&&(p->right!=NULL)){t=p; v=p->right; s=v->left;}
while(s!=NULL){
t=v;
v=s;
s=v->left;
}
if((t!=NULL)&&(t!=p)){
t->left=v->right;
v->right=p->right;
v->left=p->left;
}
if(t==p) v->left=p->left;
if(q==NULL){
cout<info<<" ildiz\n";
tree=v;
delete(p);
return tree;
}
if(p==q->left)
q->left=v;
else q->right=v;
delete(p); // o‘chirilgan element joylashgan xotira yacheykasini tozalash
return tree;
}
int main()
{ int n,key,s; node *tree=NULL,*next=NULL;
cout<<"n="; cin>>n;
for(int i=0; i
node *p=new node;
node *last=new node;
cin>>s;
p->info=s;
p->left=NULL;
p->right=NULL;
if(i==0){tree=p; next=tree; continue; }
next=tree;
while(1)
{ last=next;
if(p->infoinfo)next=next->left;
else next=next->right;
if(next==NULL)break; }
if(p->infoinfo)last->left=p;
else last->right=p;}
cout<
intrave(tree);
cout<<"delete qilinadigan elementni kiriting \n";
cout<<"key="; cin>>key;
tree=del(tree,key);
intrave(tree);
getch();
} Dostları ilə paylaş: