二叉树的遍历和应用

#include "stdio.h"
#include "malloc.h"
typedef  char ElemType; 
typedef struct BiTreeNode 
{
	ElemType data ;      //树的数据域为字符型
	struct BiTreeNode *LChild ;//*左孩子指针
	struct BiTreeNode *RChild ;
	int height;      //*右孩子指针
}BiTreeNode,*BiTree ; 

BiTree CreatBiTree()
{
	BiTree T;
	char x;
	scanf("%c",&x);
	getchar();
	if (x=='#'||x==' ') T=NULL;
	else 
	{	T=(BiTree)malloc(sizeof(BiTreeNode));
	T->data=x;
	printf(" 请输入 %c 结点的左孩子:",T->data);
	T->LChild=CreatBiTree();
	printf(" 请输入 %c 结点的右孩子:",T->data);
	T->RChild=CreatBiTree();
	}
	return T;
}

//前序递归遍历二叉树
void PreOrder(BiTree T)
{
	if(T==NULL)
		return;
	printf("%c",T->data);
	PreOrder(T->LChild);
	PreOrder(T->RChild);
}

void InOrder(BiTree T)
{
	if(T==NULL)
		return;
	InOrder(T->LChild);
	printf("%c",T->data);
	InOrder(T->RChild);
}

void postOrder(BiTree T)
{
	if(T==NULL)
		return;
	postOrder(T->LChild);
	postOrder(T->RChild);
	printf("%c",T->data);
}

int TreeHeight(BiTree T)
{
	int lh,rh;
	if (T==NULL)
		return 0;
	lh=TreeHeight(T->LChild );
	rh=TreeHeight(T->RChild );
	T->height=(lh>rh)?lh+1:rh+1;
	return T->height;
	
}

int Leafcount(BiTree T)
{
	if(!T)        	
		return 0; 
	else if (T->LChild==NULL && T->RChild ==NULL)
		return 1;
		else
			return 	(Leafcount(T->LChild)+Leafcount(T->RChild));
}
void main()
{
	BiTree T;
	int count=0;
	int height=0;
	int k;	
	do
    {  
		printf("\n\n\n\n");
		printf("\t\t\t  树 子系统\n");
		printf("\t\t******************************\n");
		printf("\t\t*        1----建二叉树    *\n");
		printf("\t\t*        2----前序遍历    *\n");
		printf("\t\t*        3----中序遍历    *\n");
		printf("\t\t*        4----后序遍历    *\n");
		printf("\t\t*        5----求树高度      *\n");
		printf("\t\t*        6----叶子个数      *\n");
		printf("\t\t*        0----返  回    *\n");
		printf("\t\t******************************\n");
		printf("\t\t 请选择菜单项(0-5):");
		scanf("%d",&k);getchar();
		if (k==1)
		{	printf("\n 请输入此树的根结点:");
		    T=CreatBiTree();                    //建立二叉树
		}
		else if (k==2)          
		{
			printf("\n   此树前序遍历的顺序:");
			PreOrder(T);             
		}
		else if (k==3)
		{	
			printf("\n   此树中序遍历的顺序:");
		    InOrder(T);           	
		}
		else if (k==4)       //查找线性表中元素值为x的位置
		{	
			printf("\n   此树后序遍历的顺序:");
			postOrder(T);             
		}
		else if (k==5)        //输出链表
		{	
			height=TreeHeight(T);            
			printf("\n此树的高度是:%d",  height); 
		}
		else if (k==6)        //输出链表
		{	
		    Leafcount(T);       
			printf("\n此树叶子结点个数是:%d", 	Leafcount(T)); 
		    
		}
	}while(k!=0);
}

**说明:**用递归实现二叉树的先序、中序、后序三种遍历。
1.这个是鄙人大二期间所学,所以模板很多人都用过,如有雷同,不是偶然。
2.发博客只为了纪念所学所感,于此而已。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SIR步步留心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值