#pragma warning(disable:4996)
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node* lchild;
struct node* rchild;
}Node,*Tree;
Tree Create()
{
Node* root = NULL;
char ch;
scanf("%c", &ch);
if (ch != '#')
{
root = (Node*)malloc(sizeof(Node));
root->data = ch;
root->lchild = Create();
root->rchild = Create();
}
else
root = NULL;
return root;
}
void Xian(Tree root)
{
if (root == NULL)
return;
printf("%c-", root->data);
Xian(root->lchild);
Xian(root->rchild);
}
void Zhong(Tree root)
{
if (root == NULL)
return;
Zhong(root->lchild);
printf("%c-", root->data);
Zhong(root->rchild);
}
void Hou(Tree root)
{
if (root == NULL)
return;
Hou(root->lchild);
Hou(root->rchild);
printf("%c-", root->data);
}
void NoXian(Tree root)
{
if (root == NULL)
{
printf("树为空!!!\n");
return;
}
Tree a[100];
int top = 0;
a[top++] = root;
while (top != 0)
{
root = a[--top];
printf("%c-", root->data);
if (root->rchild != NULL)
a[top++] = root->rchild;
if (root->lchild != NULL)
a[top++] = root->lchild;
}
return;
}
void NoZhong(Tree root)
{
if (root == NULL)
{
printf("树为空!!!\n");
return;
}
Tree a[100];
int top = 0;
a[top++] = root;
while (top != 0)
{
while (root!= NULL)
{
root = root->lchild;
a[top++] = root;
}
--top;
if (top != 0)
{
root = a[--top];
printf("%c-", root->data);
root = root->rchild;
a[top++] = root;
}
}
return;
}
void Cengci(Tree root)
{
if (root == NULL)
{
printf("树为空!!!\n");
return;
}
int i = 0, j = 0;
Tree a[100];
a[j++] = root;
while (j != i)
{
root = a[i++];
printf("%c-", root->data);
if (root->lchild != NULL)
a[j++] = root->lchild;
if (root->rchild != NULL)
a[j++] = root->rchild;
}
return;
}
//树的深度
int max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
int MaxDeep(Tree root)
{
if(root==NULL)
return 0;
return max(MaxDeep(root->lchild),MaxDeep(root->rchild))+1;
}
//求叶子结点的个数并将其打印出来
int Leff(Tree root)
{
static int number=0;//采用static函数,每次进入函数时number不会重新变成0
if(root!=NULL)
{
if(root->lchild==NULL&&root->rchild==NULL)
{
number++;
printf("%c\n",root->data);
}
Leff(root->lchild);
Leff(root->rchild);
}
return number;
}
/*另一种表示方法
int Leff(Tree root)
{
if(root==NULL)
return 0;
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
return Leff(root->lchild)+Leff(root->rchild);
}
*/
//求总的结点个数
int Count(Tree root)
{
if(root==NULL)
return 0;
else
return Count(root->lchild)+Count(root->rchild)+1;
}
int main()
{
Tree root;
printf("请以先序遍历的顺序输入你想要创建的树:\n");
root = Create();
printf("先序递归遍历结果:\n");
Xian(root);
printf("\n");
printf("中序递归遍历结果:\n");
Zhong(root);
printf("\n");
printf("后序递归遍历结果:\n");
Hou(root);
printf("\n");
printf("先序非递归遍历结果:\n");
NoXian(root);
printf("\n");
printf("中序非递归遍历结果:\n");
NoZhong(root);
printf("\n");
printf("层次非递归遍历结果:\n");
Cengci(root);
printf("\n");
printf("树的最大深度为:%d\n",MaxDeep(root));
int m=Leff(root);
printf("树的叶子结点如上,共有%d个\n",m);
printf("树的总结点数为%d\n",Count(root));
return 0;
}