1. 程式人生 > 實用技巧 >二叉樹的遞迴應用—求二叉樹葉子數量

二叉樹的遞迴應用—求二叉樹葉子數量

#include <stdio.h>
#include <stdlib.h>

typedef struct BinaryNode //二叉樹結點 
{
	//資料域 
	char data;
	//指標域 
	struct BinaryNode * lChild;  //左孩子 
	struct BinaryNode * rChild;  //右孩子 
}BiNode; 
void calculateTreeNum(BiNode * root, int * num)
{
	//終止條件
	if(NULL == root)
	{
		return;
	} 
	
	//如果節點 左子樹 與右子樹 同時為空  稱為葉子
	if(NULL == root->lChild && NULL == root->rChild)
	{
		(*num)++;
	}
	
	calculateTreeNum(root->lChild, num);
	calculateTreeNum(root->rChild, num);
} 

void test01()
{
	//對成員初始化 
	BiNode nodeA = {'A', NULL, NULL};
	BiNode nodeB = {'B', NULL, NULL};
	BiNode nodeC = {'C', NULL, NULL};
	BiNode nodeD = {'D', NULL, NULL};
	BiNode nodeE = {'E', NULL, NULL};
	BiNode nodeF = {'F', NULL, NULL};
	BiNode nodeG = {'G', NULL, NULL};
	BiNode 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;
	
	//1.計算葉子數量 
	int num = 0;
	calculateTreeNum(&nodeA, &num); //傳入樹根 
	printf("葉子數:%d", num);
	 
}
int main()
{
	test01();
	
	return 0;
}