bài của bạn tâm đây.
Mã:
#include<stdio.h>
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
//---------------
typedef struct node
{
int pt;
node *left;
node *right;
} cay;
//---------------
void make(cay **T)
{
*T=NULL;
}
//-- duyet Giua - Trai - Phai
void preorder(cay *T)
{
cay *P;
P=T;
if(P!=NULL)
{
printf("%d ",P->pt);
preorder(P->left);
preorder(P->right);
}
}
//- Duyet Trai - Giua - Phai
void inorder(cay *T)
{
cay *P;
P=T;
if(P!=NULL)
{
inorder(P->left);
printf("%d ",P->pt);
inorder(P->right);
}
}
//- Duyet Trai - Phai - Giua
void posorder(cay *T)
{
cay *P;
P=T;
if(P!=NULL)
{
posorder(P->left);
posorder(P->right);
printf("%d ",P->pt);
}
}
// dem so la---------------
int leaf(cay *T)
{
if(T==NULL)
return 0;
if(T->left==NULL && T->right==NULL)
return 1;
return leaf(T->left) + leaf(T->right);
}
// nhap cay ----------------------
void chen(cay **T,int x)
{
cay *tmp;
tmp=*T;
if(tmp==NULL)
{
tmp=new cay;
tmp->pt=x;
tmp->left=tmp->right=NULL;
(*T)=tmp;
}
else if(x<(*T)->pt)
chen(&(*T)->left,x);
else if(x>(*T)->pt)
chen(&(*T)->right,x);
else
printf("\nNut da ton tai !");
}
main()
{
cay *T,*l,*r;
make(&T);
int x;
char y;
int dk=1;
printf("\nNhap phan tu, nhan y --> [Enter]de nhap tiep !");
while(dk==1)
{
printf("\nNhap phan tu: ");
cin>>x;
chen(&T,x);
printf("\nNhap tiep y/n: ");
cin>>y;
if(y=='y')
dk=1;
else
dk=0;
}
printf("\ntien to\n");
preorder(T);
printf("\ntrung to\n");
inorder(T);
printf("\nhau to\n");
posorder(T);
printf("\nSo la: %d",leaf(T));
}
nhập cây như sau: nhập vào nút giữa, nhỏ hơn nhập sang trái nút, lớn hơn nhập sang phải.