Mavzu: Muvozanatlangan binar daraxtlar


Binar daraxtni vizuallashtirish


Download 100.91 Kb.
bet3/3
Sana28.12.2022
Hajmi100.91 Kb.
#1012821
1   2   3
Binar daraxtni vizuallashtirish
Binar daraxtni ko’rikdan o’tkazayotganda biz yuqorida har bir tugunni o’ngida va chapida turgan tugunlarni so’z bilan ifodaladik. Lekin bu usul bir muncha noqulay. Daraxtni vizual ko’rinishda ifodalash uni anglashning juda qulay usuli hisoblanadi. Daraxtni vizuallashtirishning grafik ko’rinishi va konsol oynasida ifodalash kabi turlari mavjud. Shundan konsol oynasida daraxtni vizuallashtirishni ko’rib chiqamiz. Bunda sonlar daraxt shaklida joylashtiriladi. Quyida bunday usulning dastur kodi keltirilgan.
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);

}
}


D
astur kodi quyidagi 4.10 a-rasmdagi daraxtni konsol ekranida 4.10 b-rasm ko’rinishda ifodalaydi.



4.10-rasm. A – binar daraxt; b – binar daraxtning ekranda namoyon bo’lishi


Yuqorida keltirilgan bir nechta algoritmlarni qo’llab bitta misol ko’rib chiqamiz.

Misol: berilgan binar daraxtning balandligini aniqlang va muvozanatlang.


Dastur kodi
#include
#include
Using namespace std;
Class node{

Public: int info;

Node *left;

Node *right;

};

Int k=0;



Int intrave(node *tree){

If (tree!=NULL){int a=NULL, b=NULL;

If (tree->left!=NULL){ a=tree->left->info; }

If (tree->right!=NULL){ b=tree->right->info; }

Cout»<’ngida=>»<

Intrave(tree->left);

Intrave(tree->right); }

Return 0;

}

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);

}


}

Int create_arr(node *tree,int *arr){

If(!tree) return 0;

Else{


Create_arr(tree->left,arr);

Arr[k++]=tree->info;

Create_arr(tree->right,arr);

}


}

Node *new_tree(int *arr, int start, int end)

{

If(start>end) return NULL;



Else {

Int mid=(start+end)/2;

Node *tree=new node;

Tree->info=arr[mid];

Tree->left=new_tree(arr,start,mid-1);

Tree->right=new_tree(arr,mid+1,end);

Return tree;

}


}

Void vizual(node *tree,int l)

{ int i;

If(tree!=NULL) {

Vizual(tree->right,l+1);

For (i=1; i<=l; i++) cout<<» «;

Cout

Vizual(tree->left,l+1);

}

}


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<


Intrave(tree);

Cout<<»\nya'ni\n»;

Vizual(tree,0);

Int h=height(tree);



Cout<<»balandligi=»<
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