Mavzu: Muvozanatlangan binar daraxtlar


Download 100.91 Kb.
bet2/3
Sana28.12.2022
Hajmi100.91 Kb.
#1012821
1   2   3
2.Binar daraxt balandligi
Binar daraxtning balandligi deb daraxt bosqichlari soniga aytiladi. Binar daraxt balandligini aniqlash uchun uning har bir tuguni chap va o’ng qismdaraxtlari balandliklari solishtiriladi va maksimal qiymat balandlik deb olinadi. Misol uchun quyidagi 4.9-rasmdagi daraxtning balandligi 2 ga teng.

1-rasm. Binar daraxt balandligi

Daraxt balandligini aniqlash dastur kodini keltiramiz.
Int height(node *tree){
Int h1,h2;
If (tree==NULL) return (-1);
Else {
H1 = height(tree->left);
H2 = height(tree->right);
If (h1>h2) return (1 + h1);
Else return (1 + h2);
}
}
Binar daraxtni muvozanatlanganmi yoki yo’qligini tekshirish
Daraxtning balandligini aniqlashni o’rganganimizdan keyin uning muvoza-natlanganligini tekshirish mumkin. Binar daraxtning muvozanatlanganligini tekshirish uchun uning har bir tugunini har ikkala qismdaraxti balandliklarini hisoblab, farqlarini tekshirib ko’rish kerak. Agar farq 0 yoki 1 ga teng bo’lsa, bu muvozanatlangan daraxt hisoblanadi. Quyida binar daraxtni muvozanatlanganlikka tekshirishning rekursiv funksiyasini qo’llovchi dastur keltirilgan.
Dastur kodi
#include
#include
Using namespace std;

Class node{


Public: int info;
Node *left;
Node *right;
};
Int k=0,Flag=1;
Int height(node *tree){
Int h1,h2;
If (tree==NULL) return (-1);
Else {
H1 = height(tree->left);
H2 = height(tree->right);
If (h1>h2) return (1 + h1);
Else return (1 + h2);
}
}
Void vizual(node *tree,int l)
{ int i;
If(tree!=NULL) {
Vizual(tree->right,l+1);
For (i=1; i<=l; i++) cout<<» «;
CoutVizual(tree->left,l+1);
}
}
Int AVLtree (node *tree){
Int t;
If (tree!=NULL){
T = height (tree->left) – height (tree->right);
If ((t<-1) || (t>1)) { Flag = 0; return Flag; }
AVLtree (tree->left); AVLtree (tree->right);
}
}
Int GetFlag(){return Flag;}
Int main()
{ int n,key,s; node *tree=NULL,*next=NULL;
Cout<<»n=»; cin>>n; int arr[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<<»\nbinar daraxt:\n»;
Vizual(tree,0);
AVLtree(tree);
If(GetFlag()) cout<<»ha,muvozanatlangan daraxt»; else cout<<»yo’q, muvozanatlanmagan daraxt»;cout<
Getch();
}
Dastur natijasi


Download 100.91 Kb.

Do'stlaringiz bilan baham:
1   2   3




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling