Mavzu: Muvozanatlangan binar daraxtlar
Download 100.91 Kb.
|
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.
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<<» «; Cout } } 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: |
ma'muriyatiga murojaat qiling