当前位置 : 主页 > 编程语言 > c语言 >

【每日编程】Day 5 求二叉树叶子结点的个数

来源:互联网 收集:自由互联 发布时间:2023-09-06
#includestdio.h#includestdlib.h#define OVERFLOW -2#define OK 1#define ERROR 0typedef int Status;typedef char TElemType;typedef struct BiTNode{TElemType data;struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;Status CreateBiTree(BiTree *T){char
#include<stdio.h>
#include<stdlib.h>
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef int Status;
typedef char TElemType;
typedef struct BiTNode
{
	TElemType data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status CreateBiTree(BiTree *T)
{
	char ch;
	ch=getchar();
	if(ch=='#')
		*T=NULL;
	else
	{
		(*T)=(BiTNode*)malloc(sizeof(BiTNode));
		if(!*T)
			exit(OVERFLOW);
		(*T)->data=ch;
		CreateBiTree(&(*T)->lchild);
		CreateBiTree(&(*T)->rchild);
	}
	return OK;
}
Status LeafCount(BiTree T,int *n)
{
if(T)
	{
		if(!T->lchild&&!T->rchild)
		{
			(*n)++;
			return 1;
		}
		LeafCount(T->lchild,n);
		LeafCount(T->rchild,n);
	}
	return *n;
}
Status PostOrderTraverse(BiTree T,Status (*visit)(TElemType e))
{
	if(T)
	{
		PostOrderTraverse(T->lchild,visit);
		PostOrderTraverse(T->rchild,visit);
		(*visit)(T->data);
	}
	else
		return OK;
}
Status visit(TElemType e)
{
  printf("%c\t",e);
  return OK;
}
int main()
{
	BiTree T;
	char ch;
	printf("请输入一个二叉链表:");
    CreateBiTree(&T);
    printf("\n");
    printf("后序遍历的二叉链表为:\n");
	PostOrderTraverse(T,visit);
	printf("\n"); 
	int n;
	LeafCount(T,&n); 
	printf("二叉树所有的叶子结点个数为%d",n);
    return 0;
}

【每日编程】Day 5 求二叉树叶子结点的个数_#define

网友评论