//求二叉树中叶子节点的个数
#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");
}
求二叉树中叶子节点的个数
最新推荐文章于 2022-05-18 19:55:17 发布