#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef struct BiTNode{
char data;
struct BiTNode *lchild, *rchild;
}BiTNode,*BiTree;
int Max(int x, int y)
{
return x > y ? x : y;
}
//先序建立一棵二叉树
void Create(BiTree &T)
{
char ch;
scanf("%c", &ch);
if (ch == '#') T = NULL; //T是指的是节点不是单单指树
else
{
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = ch;
Create(T->lchild);
Create(T->rchild);
}
}
//先序遍历打印二叉树
void Preorder(BiTree &root)
{
if (root != NULL)
{
printf("%c", root->data); //先序把打印放前边
Preorder(root->lchild);
Preorder(root->rchild);
}
}
//中序遍历打印二叉树
void Inorder(BiTree &root)
{
if (root != NULL)
{
Inorder(root->lchild);
printf("%c", root->data); //中序把打印放中间
Inorder(root->rchild);
}
}
//后续遍历打印二叉树
void Postorder(BiTree &root)
{
if (root != NULL)
{
Postorder(root->lchild);
Postorder(root->rchild);
printf("%c", root->data); //后续就把打印放最后
}
}
//先序遍历输出叶子结点
void Preorderleaf(BiTree &root)
{
if (root != NULL)
{
if (root->lchild == NULL&&root->rchild == NULL) //判断是否是叶子
printf("%c", root->data);
Preorderleaf(root->lchild);
Preorderleaf(root->rchild);
}
}
//统计叶子节点的个数
int LeafCount(BiTree &root)
{
int leaf;
if (root == NULL) //树空
leaf = 0;
else if (root->lchild == NULL&&root->rchild == NULL) //只有根节点
leaf = 1;
else
leaf = LeafCount(root->lchild) + LeafCount(root->rchild); //左右子树都不为空
return leaf;
}
//统计树的高度
int BiTreeDepth(BiTree &root)
{
if (!root) return 0;
int lh = BiTreeDepth(root->lchild);
int rh = BiTreeDepth(root->rchild);
return lh > rh ? lh + 1 : rh + 1;
}
void operate()
{
BiTree MyBiTree;
printf("请输入节点序列(注:①输入连续‘#’个数m大于连续的字母个数n时前第m-1个节点无左右孩子;\n\
②连续的#个数x-1=y是用来划分前第y个字母左右子树的。):\n");
Create(MyBiTree); //创建树
printf("先序遍历树:");
Preorder(MyBiTree); //先序遍历树
printf("\n");
printf("先序遍历树:");
Inorder(MyBiTree); //中序遍历树
printf("\n");
printf("先序遍历树:");
Postorder(MyBiTree); //后续遍历树
printf("\n");
printf("叶子结点:");
Preorderleaf(MyBiTree);
printf("\n");
printf("叶子节点的个数为:%d\n", LeafCount(MyBiTree));
printf("树的深度为:%d\n", BiTreeDepth(MyBiTree));
}
int main()
{
operate()<span style="font-family: Arial, Helvetica, sans-serif;">;</span>
return 0;
}
输入示例: