tao cây-đếm lá,nút tổng cay
#include<conio.h>
#include<iostream.h>
#include<stdio.h>
typedef struct NUT
{
int Dulieu;
NUT * Left,* Right;
} ;
typedef NUT*Cay;
// cau 1
NUT*Taonut(int x,NUT*L,NUT*R)
{
NUT*e=new NUT;
e->Dulieu=x;
e->Left=L;
e->Right=R;
return e;
}
// cau 2
void Taocay(Cay & t)
{
NUT*m,*h,*b,*s;
m=Taonut(22,NULL,NULL);
h=Taonut(23,m,NULL);
s=Taonut(27,NULL,NULL);
b=Taonut(25,h,s);
t=b;
}
//cau 3
void Duyetphai(Cay t)
{
if(t!=NULL)
{
Duyetphai(t->Right);
cout<<t->Dulieu<<" ";
Duyetphai(t->Left);
}
}
//cau 4
int Demnut(Cay t)
{
if(t==NULL)
return 0;
else
return 1+Demnut(t->Right)+Demnut(t->Left);
}
// cau 5
void Them(int x, Cay & t)
{
NUT*e=new NUT;
e->Dulieu=x;
e->Left=NULL;
e->Right=NULL;
if(t==NULL)
t=e;
else
if(x<t->Dulieu)
Them(x,t->Left);
else
if(x>t->Dulieu)
Them(x,t->Right);
else
cout<<" da co x tren cay";
}
// cau 6
int Tong(Cay t)
{
int S=0;
if(t!=NULL)
S+=t->Dulieu+Tong(t->Left)+Tong(t->Right);
return S;
}
//cau 7
int Demla(Cay t)
{
if(t==NULL)
return 0;
else
{
if((t->Left==NULL) &&( t->Right==NULL))
return 1;
else
return Demla(t->Left)+Demla(t->Right);
}
}
void Duyettrai(Cay t)
{
if(t!=NULL)
{
Duyettrai(t->left);
cout<<t->Dulieu<<" ";
Duyettrai(t->right);
}
}
void Duyetgiua(Cay t)
{
if(t!=NULL)
{
cout<<t->Dulieu<<" ";
Duyetgiua(t->Left);
Duyetgiua(t->Right);
}
}
void main()
{
clrscr();
Cay t;
Taocay(t);
Duyetphai(t);
int S;
S=Tong(t);
cout<<"
tong cay ="<<S;
int a,b;
b=Demla(t);
cout<<"
so la cay ="<<b;
a=Demnut(t);
cout<<"
so nut cua cay la "<<a;
cout<<"
them 20 vao cay";
Them(20,t);
Duyetphai(t);
b=Demla(t);
cout<<"
so la cay sau khi chen ="<<b;
a=Demnut(t);
cout<<"
so nut sau khi them la "<<a;
S=Tong(t);
cout<<"
Tong sau khi them ="<<S;
getch();
}
Bạn đang đọc truyện trên: Truyen247.Pro