Ўзбекистон республикаси ахборот технологиялари ва коммуникацияларини ривожлантириш вазирлиги


Download 248.48 Kb.
bet2/2
Sana20.10.2020
Hajmi248.48 Kb.
#135084
1   2
Bog'liq
Lab

a. b.

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<info<<"--chapida=>"<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<info<

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="<

create_arr(tree,arr);

for(int i=0;i

tree=new_tree(arr,0,k-1);

vizual(tree,0);

getch();

}

Dastur natijasi


Download 248.48 Kb.

Do'stlaringiz bilan baham:
1   2




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