二叉树的基本操作(二)

24 篇文章 1 订阅
11 篇文章 0 订阅

这是对二叉树(一)的补充

<span style="font-size:18px;">#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
#define MaxWidth 40
int LeafCount=0;
int Layer=1;
typedef char ElemType;
typedef struct tnode
{
	ElemType data;
	struct tnode *lchild,*rchild;
} BTNode;
void CreateBTree(BTNode * &bt) /*创建二叉链bt*/
{
	BTNode * p=NULL;
	char  ch;
	bt=NULL;
	ch=getchar(); /*先序输入序列AB.DF..G..C.E.H..*/
	if (ch=='.') 
		bt=NULL;
	else
	{
	  	bt=(BTNode *)malloc(sizeof(BTNode));
	       bt->data=ch;
	    CreateBTree( bt->lchild);
	    CreateBTree( bt->rchild);
	}
}
void PreDispBTree(BTNode *bt) /*先序输出二叉树*/
{
	if (bt!=NULL)
	{ 
		printf("%c ",bt->data);
		PreDispBTree(bt->lchild);/*递归处理左子树*/
		PreDispBTree(bt->rchild);/*递归处理右子树*/
	}
}
void zhongxuTree(BTNode *bt)/*编写中序输出二叉树函数*/
{
	if(bt!=NULL)
	{
		zhongxuTree(bt->lchild);
		printf("%c ",bt->data);
		zhongxuTree(bt->rchild);
	}
}
void houxuTree(BTNode *bt)    /*编写后序输出二叉树函数*/
{
	if(bt!=NULL)
	{
		houxuTree(bt->lchild);
		houxuTree(bt->rchild);
		printf("%c ",bt->data);
	}
}  
void yeziTree(BTNode *bt)/*编写二叉树输出叶子节点的函数*/
{
	if(bt!=NULL)
	{
		if(bt->lchild==NULL&&bt->rchild==NULL)
		{
			printf("%c ",bt->data);
		}
		yeziTree(bt->lchild);
		yeziTree(bt->rchild);
	}
}
int  leaf(BTNode *bt)/*统计叶子数*/
{
	if(bt!=NULL)
	{
		leaf(bt->lchild);
		leaf(bt->rchild);
		if(bt->lchild==NULL&&bt->rchild==NULL)
			LeafCount++;
	}
	return LeafCount;
}
int shenduTree(BTNode *bt)/*计算并输出二叉树的深度。*/
{
	int hl,hr,max;
	if(bt!=NULL)
	{
		hl=shenduTree(bt->lchild);
		hr=shenduTree(bt->rchild);
		max=hl>hr? hl:hr;
		return (max+1);
	}
	else
			return 0;
	}
void PrintTree(BTNode *bt,int Layer)/*编写竖向显示二叉树(即按层显示)函数*/
{
	if(bt==NULL)
		return ;
    PrintTree(bt->lchild,Layer+1);
	for(int i=0;i<Layer;i++)
		printf("  ");
	printf("%c\n",bt->data);
	PrintTree(bt->rchild,Layer+1);
}
int main(void)
{
	BTNode *bt;
	CreateBTree(bt);/*构造图6.12(a)所示的二叉树*/
	printf("二叉树先序序列bt:\n");
	   PreDispBTree(bt);
	    printf("\n");
	printf("二叉树中序序列bt:\n");/*中序输出二叉树*/
	    zhongxuTree(bt);
	printf("\n");
	    printf("二叉树后序序列bt:\n");/*后序输出二叉树*/
	    houxuTree(bt);
	printf("\n");
	    printf("计算并输出二叉树的深度\n");
	    printf("%d\n", shenduTree(bt));
	    printf("输出二叉树bt叶子结点:\n");/*输出二叉树叶子结点*/
	yeziTree(bt);
	printf("\n");
	printf("输出二叉树bt叶子结点个数:\n");/*输出二叉树叶子结点个数*/
	printf("%d\n",leaf(bt));
	printf("树状打印二叉树:\n");
	PrintTree(bt,Layer);
	printf("\n");
	return 0;
}</span>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值