求二叉树中叶子节点的个数

//求二叉树中叶子节点的个数

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

//二叉树的存储表示 
typedef char TElemType;
typedef struct BiTNode {
	TElemType data;
	struct BiTNode *lchild, *rchild;	//左右孩子指针 
}BiTNode, *BiTree;


//计算叶结点的个数 
//返回叶结点的个数 
int CalLeafNum(BiTree t) {
	//请在此填写代码 
	//左子树的叶子节点+右子树的叶子节点
	if (t == NULL) return 0;//空树
	int count = 0;
	if (t->lchild ==NULL && t->rchild ==NULL) return 1;//只有根节点
	int lsize = CalLeafNum(t->lchild);//统计左子树
	int rsize = CalLeafNum(t->rchild);//统计右子树
	return lsize + rsize;
}

BiTree CreateBitree(TElemType inorder[], TElemType postorder[], int lowin, int highin, int lowpost, int highpost)
{
	BiTree t = (BiTree)malloc(sizeof(BiTNode));
	t->data = postorder[highpost];//对于后序遍历,最后一个肯定是根节点
	t->lchild = t->rchild = NULL;//初始化根节点的左右孩子节点
	for (int pos = lowin; pos <= highin; pos++) {
		if (inorder[pos] == postorder[highpost]) {
			if (pos != lowin)
				t->lchild = CreateBitree(inorder, postorder, lowin, pos - 1, lowpost, lowpost + pos - lowin - 1);//左二叉树建立
			if (pos != highin)
				t->rchild = CreateBitree(inorder, postorder, pos + 1, highin, highpost - pos + lowin, highpost - 1);//右二叉树建立
			break;
		}
	}

	return t;
}

int main()
{
	TElemType in[] = "FDGBAHEC";//中序 
	TElemType post[] = "FGDBHECA";	//后序 
	BiTree t;
	t = CreateBitree(in, post, 0, strlen(in) - 1, 0, strlen(post) - 1);
	printf("%d", CalLeafNum(t));
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值