读入二叉树的中序和后序遍历,输出此二叉树的前序遍历和叶子节点个数

本文介绍了一种根据给定的中序和后序遍历序列构建二叉树的方法,并实现了二叉树的前序遍历及计算叶子节点数量的功能。通过C语言实现,程序包括了二叉树节点的定义、构建过程、遍历输出以及叶子节点计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "malloc.h"

typedef char DataType;

/*读入二叉树的中序和后序遍历,输出此二叉树的前序遍历和叶子节点个数
测试数据
DGBAECHF
GDBEHFCA
前序遍历:ABDGCF
*/
/*定义二叉树结构体*/
typedef struct tree
{
DataType d;
struct tree *lchild,*rchild;
}Tree,*PTree;

/*in表示中序字符串 post 表示后序字符串 ins ine分别表示中序字符串的起始长度 posts poste 分别表示后序字符串的起始长度*/
void makeTree(PTree *p,char *in,int ins,int ine,char *post,int posts,int poste)
{
int preIndex=0;//定义中序字符串中 中间数的位置
if(poste<posts||ine<ins) *p=NULL;
else
{
*p=(PTree)malloc(sizeof(Tree));
(*p)->d=post[poste];
//(*p)->lchild=NULL;
//(*p)->rchild=NULL;
for(preIndex=ins;preIndex<=ine;preIndex++)
{
if(post[poste]==in[preIndex])
{
makeTree(&(*p)->lchild,in,ins,preIndex-1,post,posts,preIndex-ins-1);
makeTree(&(*p)->rchild,in,preIndex+1,ine,post,preIndex-ins,poste-1);
break;
}
}
/*该函数每次从0开始
while(9)
{
if(in[preIndex]==post[poste])break;
preIndex++;
}*/

}
}
/*前序遍历二叉树*/
void preOrder(PTree p)
{
if(p)
{
printf("%c",p->d);
preOrder(p->lchild);
preOrder(p->rchild);
}
}
/*求叶子节点数*/
int leafNum(PTree p)
{
if(p==NULL)
return 0;
else
if(p->lchild==NULL&&p->rchild==NULL)
return 1;
else
return leafNum(p->lchild)+leafNum(p->rchild);
}
void main()
{
char in[100],post[100];
int il,pl;
PTree p;
printf("输入中序\n");
gets(in);
printf("输入后序\n");
gets(post);
il=strlen(in);
pl=strlen(in);
makeTree(&p,in,0,strlen(in)-1,post,0,strlen(post)-1);
printf("前序遍历:");
preOrder(p);
printf("\n叶子节点数为%d\n",leafNum(p));

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值