1. 程式人生 > >二叉樹程式設計實戰_求葉子節點數目

二叉樹程式設計實戰_求葉子節點數目

統計二叉樹中葉子結點的個數: 葉子節點:沒有孩子節點的樹 demo.cpp

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string>
//二叉樹結點
typedef struct BINARYNODE{
	char ch;
	struct BINARYNODE *lchild;
	struct BINARYNODE *rchild;
}BinaryNode;

//遞迴遍歷
void CaculateLeafNum(BinaryNode*root,int *num){
	if (root == NULL)
	{
		return;
	}
	//沒有左右樹
	if (root->lchild==NULL && root->rchild==NULL)
	{
		(*num)++;
		printf("%c\n", root->ch);
	}
	CaculateLeafNum(root->lchild,num);
	CaculateLeafNum(root->rchild, num);

}
void CreateBinaryTree(int *num){
	//生成結點
	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;
	CaculateLeafNum(&node1, num);
	
}


int main(void){
	int num=0;//個數
	CreateBinaryTree(&num);
	printf("%d", num);
	system("pause");
	return 0;
}