递归特性求树的高度流程图
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//二叉树的节点结构体
struct BinaryNode
{
char ch;//显示的字母
struct BinaryNode * lChild;//左孩子
struct BinaryNode * rChild;//右孩子
};
//统计叶子的数量
void calculateLeafNum(struct BinaryNode * root,int *p)
{
if (root==NULL)
{
return;
}
//统计叶子
if (root->lChild == NULL && root->rChild==NULL)
{
(*p)++;
}
calculateLeafNum(root->lChild, p);
calculateLeafNum(root->rChild, p);
}
//统计树的高度
int getTreeHeight(struct BinaryNode * root)
{
if (root == NULL)
{
return 0;
}
//获取左子树的高度
int lHeight = getTreeHeight(root->lChild);
//获取右子树的高度
int rHeight = getTreeHeight(root->rChild);
//取大的值 +1 就是树的高度
int height = lHeight > rHeight ? lHeight + 1 : rHeight + 1;
return height;
}
void test01()
{
//创建节点
struct BinaryNode nodeA = { 'A',NULL,NULL };
struct BinaryNode nodeB = { 'B',NULL,NULL };
struct BinaryNode nodeC = { 'C',NULL,NULL };
struct BinaryNode nodeD = { 'D',NULL,NULL };
struct BinaryNode nodeE = { 'E',NULL,NULL };
struct BinaryNode nodeF = { 'F',NULL,NULL };
struct BinaryNode nodeG = { 'G',NULL,NULL };
struct BinaryNode nodeH = { 'H',NULL,NULL };
//建立节点之间关系
nodeA.lChild = &nodeB;
nodeA.rChild = &nodeF;
nodeB.rChild = &nodeC;
nodeC.lChild = &nodeD;
nodeC.rChild = &nodeE;
nodeF.rChild = &nodeG;
nodeG.lChild = &nodeH;
//统计二叉树叶子数量
int num = 0;
calculateLeafNum(&nodeA, &num);
printf("树的叶子数量为:%d\n", num);
//统计树的高度
int height = getTreeHeight(&nodeA);
printf("树的高度为:%d\n", height);
}
int main()
{
test01();
system("pause");
return EXIT_SUCCESS;
}