[C語言]二叉樹計算-求葉子結點數目,樹的高度


利用遞歸求下圖的葉子結點數量以及樹的深度

在這里插入圖片描述

#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;
	}
	//深度初始化為0
	int depth = 0;
	//分別求左右子樹的深度
	int LeftDepth = CalculateTreeDepth(root->lchild);
	int RightDepth = CalculateTreeDepth(root->rchild);
	//取二者中最大值,並加1(本層高度)
	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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM