#include"stdio.h"
#include"string.h"
#define Max 20
typedef struct node{
char data;
struct node *lchild,*rchild;
}BinTNode;
typedef BinTNode *BinTree;
int NodeNum,leaf;
BinTree CreatBinTree(void)
{
BinTree T;
char ch;
if((ch=getchar())=='#')
return(NULL);
else{
T=(BinTNode *)malloc(sizeof(BinTNode));
T->data=ch;
T->lchild=CreatBinTree();
T->rchild=CreatBinTree();
return(T);
}
}
void Preorder(BinTree T)
{
if(T) {
printf("%c",T->data);
Preorder(T->lchild);
Preorder(T->rchild);
}
}
int TreeDepth(BinTree T)
{
int hl,hr,max;
if(T){
hl=TreeDepth(T->lchild);
hr=TreeDepth(T->rchild);
max=hl>hr? hl:hr;
NodeNum=NodeNum+1;
if(hl==0&&hr==0) leaf=leaf+1;
return(max+1);
}
else return(0);
}
void Levelorder(BinTree T)
{
int front=0,rear=1;
BinTNode *cq[Max],*p;
cq[1]=T;
while(front!=rear)
{
front=(front+1)%NodeNum;
p=cq[front];
printf("%c",p->data);
if(p->lchild!=NULL){
rear=(rear+1)%NodeNum;
cq[rear]=p->lchild;
}
if(p->rchild!=NULL){
rear=(rear+1)%NodeNum;
cq[rear]=p->rchild;
}
}
}
void main()
{
BinTree root;
int i,depth;
printf("\n");
printf("Creat Bin_Tree; Input preorder:");
root=CreatBinTree();
do {
printf("\t********** select ************\n");
printf("\t1: Preorder Traversal\n");
printf("\t2: Iorder Traversal\n");
printf("\t3: Postorder traversal\n");
printf("\t4: PostTreeDepth,Node number,Leaf number\n");
printf("\t5: Level Depth\n");
printf("\t0: Exit\n");
printf("\t*******************************\n");
scanf("%d",&i);
switch (i){
case 1: printf("Print Bin_tree Preorder: ");
Preorder(root);
break;
case 2: printf("Print Bin_Tree Inorder: ");
Inorder(root);
break;
case 3: printf("Print Bin_Tree Postorder: ");
Postorder(root);
break;
case 4: depth=TreeDepth(root);
printf("BinTree Depth=%d BinTree Node number=%d",depth,NodeNum);
printf(" BinTree Leaf number=%d",leaf);
break;
case 5: printf("LevePrint Bin_Tree: ");
Levelorder(root);
break;
default: exit(1);
}
printf("\n");
} while(i!=0);
}
- 1
- 2
前往页