二叉树的前序、中序、后序遍历,以及叶子数目,树的深度
#define _CRT_SECURE_NO_WARNGINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct bintree
{
char c;
struct bintree * lchild;
struct bintree * rchild;
}bintree;
//遍历二叉树
void Recursion(bintree* node)
{
if (node == NULL)
{
return;
}
//printf("%c ", node->c);
//先序遍历
Recursion(node->lchild);
//中序遍历
//printf("%c ", node->c);
Recursion(node->rchild);
//后序遍历
printf("%c ", node->c);
}
//计算叶子数
int Allnode = 0;
void LeafNum(bintree* node)
{
if (node == NULL)
{
return;
}
//代码能执行进来就把自身这个叶子加进去
Allnode++;
LeafNum(node->lchild);
LeafNum(node->rchild);
}
//计算树的深度
int DepthOfTree(bintree* node)
{
int depth = 0;
if (node == NULL)
{
return depth;
}
int ldepth=DepthOfTree(node->lchild);
int rdepth=DepthOfTree(node->rchild);
depth =(ldepth>rdepth)? ++ldepth : ++rdepth;
return depth;
}
int main(void)
{
//初始化树结点
bintree root= { 'A', NULL, NULL };
bintree ch1 = { 'B', NULL, NULL };
bintree ch2 = { 'C', NULL, NULL };
bintree ch3 = { 'D', NULL, NULL };
bintree ch4 = { 'E', NULL, NULL };
bintree ch5 = { 'F', NULL, NULL };
bintree ch6 = { 'G', NULL, NULL };
bintree ch7 = { 'H', NULL, NULL };
bintree ch8 = { 'I', NULL, NULL };
root.lchild = &ch1;
root.rchild = &ch2;
ch1.rchild = &ch3;
ch2.lchild = &ch4;
ch3.lchild = &ch5;
ch3.rchild = &ch6;
ch4.lchild = &ch7;
ch4.rchild = &ch8;
//遍历打印树结点
Recursion(&root);
//求叶子节点的数目
printf("\n");
int leafnum = 0;
LeafNum(&root);
leafnum = Allnode - 1;
printf("The num of leaf is %d\n", leafnum);
//求树的深度
printf("\n");
int Depthtree = DepthOfTree(&root);
printf("The depth of the tree is %d\n", Depthtree);
system("pause");
return 0;
}
浙公网安备 33010602011771号