#include<stdio.h>
#include<malloc.h>
typedef struct tree{
char data;
struct tree *lchild,*rchild;
}bitnode;
typedef bitnode *bitree;
bitnode T;int m = 0;
bitree creat(bitnode *T1){
char ch;m++;
printf("进来%d次\n",m);
printf("输入根:");
scanf("%c",&ch);
getchar();
if(ch == '#')T1 = NULL;
else{
if(m != 1){
if(!(T1=(bitnode*)malloc(sizeof(bitnode)))){
printf("error");
}return;
}
T1->data = ch;
printf("%c's left child:\n",T1->data);
T1->lchild = creat(T1->lchild);
printf("%c's right child:\n",T1->data);
T1->rchild = creat(T1->rchild);
}
return T1;
}
void previsit(bitree T1){
if(T1 != NULL){
printf("%c",T1->data);
previsit(T1->lchild);
previsit(T1->rchild);
}
}
void cenevisit(bitree T1){
if(T1 != NULL){
previsit(T1->lchild);
printf("%c",T1->data);
previsit(T1->rchild);
}
}
void afevisit(bitree T1){
if(T1 != NULL){
previsit(T1->lchild);
previsit(T1->rchild);
printf("%c",T1->data);
}
}
int nodedep(bitnode *b){
int lchilddep,rchilddep;
if(b == NULL)
return 0;
else{
lchilddep = nodedep(b->lchild);
rchilddep = nodedep(b->rchild);
return(lchilddep>rchilddep)?(lchilddep+1):(rchilddep+1);
}
}
int nodes(bitnode *b){
int num1,num2;
if(b == NULL)
return 0;
else if(b->lchild == NULL && b->rchild == NULL)
return 1;
else{
num1 = nodes(b->lchild);
num2 = nodes(b->rchild);
return(num1 + num2 + 1);
}
}
int leafnodes(bitnode *b){
int num1,num2;
if(b == NULL)
return 0;
else if(b->lchild == NULL && b->rchild == NULL)
return 1;
else{
num1 = nodes(b->lchild);
num2 = nodes(b->rchild);
return(num1 + num2);
}
}
void disleaf(bitnode *b){
if(b != NULL)
if(b->lchild == NULL && b->rchild == NULL)
printf("%c",b->data);
else{
disleaf(b->lchild);
disleaf(b->rchild);
}
}
void nodedeg(bitnode *b,char c){
if(b == NULL)
return;
else{
if(b->lchild == NULL && b->rchild == NULL && b->data == c){
printf("%c 的度为:%d\n",c,0);
return;
}
else if(b->lchild == NULL && b->rchild != NULL ||b->lchild != NULL && b->rchild == NULL){
printf("%c 的度为:%d\n",c,1);
return;
}
else{
if(b->data == c){
printf("%c 的度为:%d\n",c,2);
return;
}
}
nodedeg(b->lchild,c);
nodedeg(b->rchild,c);
}
}
void print(bitnode *b){
if(b != NULL){
printf("%c",b->data);
if(b->lchild != NULL || b->rchild != NULL){
printf("(");
print(b->lchild);
if(b->rchild != NULL)
printf(",");
print(b->rchild);
printf(")");
}
}
}
void main(){
printf("创建二叉树:\n");
creat(&T);
printf("完成\n");
printf("先序遍历:");
previsit(&T);
printf("完成\n");
printf("中序遍历:");
cenevisit(&T);
printf("完成\n");
printf("后序遍历:");
afevisit(&T);
printf("完成\n");
printf("深度:");
nodedep(&T);
printf("完成\n");
printf("层数:");
nodedep(&T);
printf("完成\n");
printf("节点个数:");
nodes(&T);
printf("完成\n");
printf("输出:");
print(&T);
printf("完成\n");
}
|