二叉树前、中、后序遍历,求树的高度,叶子结点个数完整代码


#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define NO 0
#define ERROR 0
#define YES 1

/*定义二叉树结构体*/
typedef struct Node
{
	char data;
	struct Node* LChild;
	struct Node* RChild;
} BiNode, *BiTree;

int LeafCount=0,hl=0,hr=0;//全局变量 
/*创建二叉树*/
/*用递归法创建二叉树*/
BiNode* CreatBiTree()
{
	char ch;
	ch = getchar();
	
	if(ch == '#')
		return NULL;
	else
	{
		BiNode* T = (BiNode*)malloc(sizeof(BiNode));
		if(T == NULL)
		exit(0);
		T->data = ch;
		T->LChild = CreatBiTree();
		T->RChild = CreatBiTree();
		return T;
	}	
}

//用先序的方法遍历二叉树 
void OnBiTree(BiNode* T)
{
	if(T)
	{
     	printf("%c ", T->data);
		OnBiTree(T->LChild);
		OnBiTree(T->RChild);
	}
}

//中序的方法遍历二叉树 
void InBiTree(BiNode* T)
{
	if(T)
	{
		InBiTree(T->LChild);
		printf("%c ", T->data);
		InBiTree(T->RChild);
	}
}

//后序的方法遍历二叉树 
void UnderBiTree(BiNode* T)
{
	if(T)
	{
		UnderBiTree(T->LChild);
		UnderBiTree(T->RChild);
		printf("%c ", T->data);
	}	
} 

//输出二叉树的叶子结点
void PreOrder(BiNode* T)
{
	
	if(T!=NULL)
	{
		if(T->LChild==NULL&&T->RChild==NULL)
		printf("%c ",T->data);//输出叶子结点 
		PreOrder(T->LChild);//先序遍历做左子树 
		PreOrder(T->RChild);//先序遍历右子树 
	}
 } 
  
//统计二叉树中叶子结点的个数
void Leaf(BiNode* T)
{
	if(T!=NULL)
	{
		Leaf(T->LChild);
		Leaf(T->RChild);
		if(T->LChild==NULL&&T->RChild==NULL)
		LeafCount++;
	}
}

//求二叉树左子树高度
void PostTreeDepthLeft(BiNode* T)
{
	
	if(T!=NULL)
	{
	PostTreeDepthLeft(T->LChild);
	hl++;
	}
}

//求二叉树右子树高度
void PostTreeDepthRight(BiNode* T)
{
	
	if(T!=NULL)
	{
	PostTreeDepthRight(T->LChild);
	hr++;
	}
}
//求二叉树的高度
void PostTreeDepth(BiNode* T)
{
	if(hl>hr) 
	printf("%d",hl);
	else if(hl<hr)
		printf("%d",hr);
		else
			printf("%d",hl=hr);
}
//按横向树显示二叉树
void PrintTree(BiNode* T,int nLayer)
{
	int i;
	if(T==NULL) 
	return;
	PrintTree(T->RChild,nLayer+1);
	for(i=0;i<nLayer;i++)
		printf("   ");
	printf("%c\n",T->data);
	PrintTree(T->LChild,nLayer+1);
	
} 
int main()
{
	int nLayer=0;
	BiNode* T = NULL;
	T = CreatBiTree(); 
	printf("前序遍历结果:");
	OnBiTree(T);
	printf("\n中序遍历结果:");
	InBiTree(T);
	printf("\n后序遍历结果:");
	UnderBiTree(T);
	printf("\n二叉树中的叶子结点:"); 
	PreOrder(T);
	printf("\n输出叶子结点的个数: ");
	Leaf(T);
   	printf("%d",LeafCount);
   	printf("\n求二叉树的深度:");
   	PostTreeDepthRight(T);
   	PostTreeDepthLeft(T);
   	PostTreeDepth(T);
	printf("\n按横向树显示二叉树:\n");
	PrintTree(T,nLayer);
	return 0;
}

代码来自:@zhanglingyun123456

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值