PS:如果手机显示不完全可以用电脑查看
#include <stdio.h>
#include<stdlib.h>
#define ok 1
#define error 0
#define overflow -1
typedef char telemtype;
typedef int status;
typedef struct bitnode{
telemtype data;
struct bitnode *lchild, *rchild;
}bitnode, *bitree;
status createbitree(bitree &t) {
char ch;
ch = getchar();
if (ch == '#') t = NULL;
else {
if (!(t = (bitnode*)malloc(sizeof(bitnode)))) exit(overflow);
t->data = ch;
createbitree(t->lchild);
createbitree(t->rchild);
}
return ok;
}
status preordertraverse(bitree t)//前序遍历
{
if (t) {
printf("%c", t->data);
preordertraverse(t->lchild);
preordertraverse(t->rchild);
};
return ok;
}
status inordertraverse(bitree t)//中序遍历
{
if (t) {
inordertraverse(t->lchild);
printf("%c", t->data);
inordertraverse(t->rchild);
};
return ok;
}
status postordertraverse(bitree t)//后序遍历
{
if (t) {
postordertraverse(t->lchild);
postordertraverse(t->rchild);
printf("%c", t->data);
};
return ok;
}
int leafnum(bitree t)
{
static int num = 0;//因为是递归调用,所以用静态变量
if (t)
{
if (t->lchild == NULL&&t->rchild == NULL)//左右孩子为空则为叶子节点
num++;
leafnum(t->lchild);
leafnum(t->rchild);
}
return num;
}
int notleafnum(bitree t)//节点数
{
static int n = 0;
if (t)
{
n++;
notleafnum(t->lchild);
notleafnum(t->rchild);
}
return n;
}
int depth(bitree t)//树的深度
{
if (t == NULL)
return 0;
else
{
int m = depth(t->lchild);
int n = depth(t->rchild);
if (m > n) return (m + 1);
else return (n + 1);
}
}
status destroybitree(bitree &t)//销毁树
{
if (t)
{
destroybitree(t->lchild);
destroybitree(t->rchild);
free(t);
t = NULL;
}
return ok;
}
int main()
{
bitree bt;
printf("please input char:");
createbitree(bt);
printf("preordertraverse is:");
preordertraverse(bt);
printf("\n");
printf("inordertraverse is:");
inordertraverse(bt);
printf("\n");
printf("postordertraverse is:");
postordertraverse(bt);
printf("\n");
printf("leafnum=%d\n", leafnum(bt));
printf("notleafnum=%d\n", notleafnum(bt));
printf("depth=%d\n", depth(bt));
destroybitree(bt);
inordertraverse(bt);
system("pause");
return 0;
}