数据结构273:统计二叉树中的叶子结点数

问题描述

建立二叉链表,统计二叉树中的叶子结点数并输出。

输入说明

按照完全二叉树的形式输入二叉树的各结点数据(字符),其中虚结点用’@‘表示。输入以’#'结束。

输出说明

输出叶子结点的个数及具体值。第一行为叶子结点的数据值,各数据用空格分隔,第二行为叶子结点的个数。

输入样例

abc@@de#

输出样例

b d e
3

#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
	char data;
	struct node *lchild,*rchild;
}bitree;
bitree *root;
int creat(bitree *root)
{
	char ch;
	bitree *q[100],*s;
	int f=1,r=0,n,i;
	root=NULL;
	while((ch=getchar())!='#')
	{
		s=NULL;
		if(ch!='@')
		{
			s=(bitree*)malloc(sizeof(bitree));
			s->data=ch;
			s->lchild=NULL;
			s->rchild=NULL;
		}
		r++;
		q[r]=s;
		if(r==1) root=s;
		else
		{
			if(s&&q[f])
			{
				if(r%2==0) q[f]->lchild=s;
				else q[f]->rchild=s;
			}
			if(r%2==1) f++;
		}
	}
	n=0;
	for(i=1;i<=r;i++)
	{
		if(q[i]!=NULL&&q[i]->lchild==NULL&&q[i]->rchild==NULL&&q[i]->data!='@')
		{
			printf("%c",q[i]->data);
			if(i!=r) printf(" ");
			n++;
		}
	}
	printf("\n");
	return n;
}
int main()
{
	int n;
	root=(bitree*)malloc(sizeof(bitree));
	n=creat(root);
	printf("%d",n);
	return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值