利用递归求下图的叶子结点数量以及树的深度
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct BINARYNODE {
char ch;
struct BINARYNODE* lchild;
struct BINARYNODE* rchild;
}BinaryNode;
void CalculateLeafNum(BinaryNode* root,int *LeafNum) {
if (root == NULL) {
return;
}
if (root->lchild == NULL && root->rchild == NULL) {
(*LeafNum)++;
}
CalculateLeafNum(root->lchild,LeafNum);
CalculateLeafNum(root->rchild,LeafNum);
}
int CalculateTreeDepth(BinaryNode* root) {
if (root == NULL) {
return 0;
}
int depth = 0;
int LeftDepth = CalculateTreeDepth(root->lchild);
int RightDepth = CalculateTreeDepth(root->rchild);
depth = LeftDepth > RightDepth ? LeftDepth + 1: RightDepth + 1;
return depth;
}
void CreateBinaryTree() {
BinaryNode node1 = { 'A',NULL,NULL };
BinaryNode node2 = { 'B',NULL,NULL };
BinaryNode node3 = { 'C',NULL,NULL };
BinaryNode node4 = { 'D',NULL,NULL };
BinaryNode node5 = { 'E',NULL,NULL };
BinaryNode node6 = { 'F',NULL,NULL };
BinaryNode node7 = { 'G',NULL,NULL };
BinaryNode node8 = { 'H',NULL,NULL };
node1.lchild = &node2;
node1.rchild = &node6;
node2.rchild = &node3;
node3.lchild = &node4;
node3.rchild = &node5;
node6.rchild = &node7;
node7.lchild = &node8;
int LeafNum = 0;
CalculateLeafNum(&node1,&LeafNum);
printf("LeafNum = %d\n", LeafNum);
int Depth = CalculateTreeDepth(&node1);
printf("TreeDepth = %d\n", Depth);
}
int main() {
CreateBinaryTree();
return 0;
}
运算结果
LeafNum = 3
TreeDepth = 4