Cấu trúc dữ liệu: Cây nhị phân

#include <stdio.h>
#include <malloc.h>
typedef int DataType;
typedef struct
Node{
DataType Data;
Node* Left;
Node* Right;
};


typedef
Node* Tree;

void
MakeNullTree(Tree &T){
T=NULL;
}

int
EmptyTree(Tree T){
return
T==NULL;
}


Tree Create2(DataType V,Tree Left,Tree Right){
Tree T = (Node*)malloc(sizeof(Node));
T->Data = V;
T->Left = Left;
T->Right = Right;
return
T;
}

void
PreOrder(Tree T){
if
(T!=NULL){
printf("%d ",T->Data);
PreOrder(T->Left);
PreOrder(T->Right);
}
}

void
InOrder(Tree T){
if
(T!=NULL){
InOrder(T->Left);
printf("%d ",T->Data);
InOrder(T->Right);
}
}


void
PostOrder(Tree T){
if
(T!=NULL){
PostOrder(T->Left);
PostOrder(T->Right);
printf("%d ",T->Data);
}
}

int
IsLeaf(Tree T){
return
(T->Left==NULL && T->Right==NULL);
}

//dem so nut tren cay
int NbNodes(Tree T){
if
(T==NULL)
return
0;
else
return
1+NbNodes(T->Left)+NbNodes(T->Right);
}

//dem so nut la tren cay
int NbLeaves(Tree T){
if
(T==NULL)
return
0;
else if
(IsLeaf(T))
return
1;
else
return
NbLeaves(T->Left)+NbLeaves(T->Right);
}

int
max (int a,int b){
return
(a>b)?a:b;
}

int
Height(Tree T){
if
(T==NULL || IsLeaf(T))
return
0;
else
return
1+max(Height(T->Left),Height(T->Right));
}

int
main(){
Tree T1=Create2(1,NULL,NULL);
Tree T2=Create2(2,NULL,NULL);
Tree T5=Create2(5,NULL,NULL);
Tree T3=Create2(3,NULL,NULL);
Tree T8=Create2(8,NULL,T2);
Tree T12=Create2(12,T1,NULL);
Tree T7=Create2(7,T5,T8);
Tree T6=Create2(6,T3,T12);
Tree T = Create2(9,T7,T6);
printf("Duyet tien tu:\n");
PreOrder(T);
printf("\nDuyet trung tu:\n");
InOrder(T);
printf("\nDuyet hau tu:\n");
PostOrder(T);
printf("\nIsLeaf(8) = %d",IsLeaf(T8));
printf("\nIsLeaf(1) = %d",IsLeaf(T1));
printf("\nNbNodes(T) = %d",NbNodes(T));
printf("\nNbLeaves(T) = %d",NbLeaves(T));
printf("\nHeight(T) = %d",Height(T));
return
0;
}

Bài liên quan

Bài liên quan