2024.2.7

本文介绍了如何使用C语言实现二叉树的创建、先序、中序和后序遍历,以及计算节点度和树的深度的方法。
摘要由CSDN通过智能技术生成

1、二叉树的操作

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef char datatype;
typedef struct Node
{
	//数据域
	datatype data;
	//左孩子指针
	struct Node *lchild;
	//右孩子指针
	struct Node *rchild;
}*Btree;
Btree create_node()
{
	Btree s=(Btree)malloc(sizeof(struct Node));
	if(s==NULL)
		return NULL;
	s->data=0;
	s->lchild=s->rchild=NULL;
	return s;
}
Btree create_tree()
{
	datatype element;
	printf("please enter the element:");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	//创建节点
	Btree tree=create_node();
	tree->data=element;
	//循环递归左孩子
	puts("left");
	tree->lchild=create_tree();
	//循环递归右孩子
	puts("right");
	tree->rchild=create_tree();
	return tree;
}
void first_output(Btree tree)
{
	if(tree==NULL)
		return;
	//遍历根节点
	printf("%c",tree->data);
	//遍历左孩子
	first_output(tree->lchild);
	//遍历右孩子
	first_output(tree->rchild);
}
void mid_output(Btree tree)
{
	if(tree==NULL)
		return;
	//遍历左孩子
	mid_output(tree->lchild);
	//遍历根节点
	printf("%c",tree->data);
	//遍历右孩子
	mid_output(tree->rchild);
}
void last_output(Btree tree)
{
	if(NULL==tree)
		return;
	//遍历左孩子
	last_output(tree->lchild);
	//遍历右孩子
	last_output(tree->rchild);
	//遍历根节点
	printf("%c",tree->data);
}
void count_tree(Btree tree,int *n0,int *n1,int *n2)
{
	if(tree==NULL)
		return;
	if(!tree->lchild && !tree->rchild)
		++*n0;
	else if(tree->lchild && tree->rchild)
		++*n2;
	else
		++*n1;
	//递归左孩子
	count_tree(tree->lchild,n0,n1,n2);
	//递归右孩子
	count_tree(tree->rchild,n0,n1,n2);
}
int high_tree(Btree tree)
{
	if(tree==NULL)
		return 0;
	//递归左子树
	int left=1+high_tree(tree->lchild);
	//递归右子树
	int right=1+high_tree(tree->rchild);
	return left>right?left:right;
}
int main(int argc, const char *argv[])
{
	//创建二叉树
	Btree tree=create_tree();
	//先序遍历
	first_output(tree);
	puts("");
	//中序遍历
	mid_output(tree);
	puts("");
	//后序遍历
	last_output(tree);
	puts("");
	//计算个节点的度
	int n0=0,n1=0,n2=0;
	count_tree(tree,&n0,&n1,&n2);
	printf("n0=%d n1=%d n2=%d n=%d\n",n0,n1,n2,n0+n1+n2);
	//计算树的深度
	int high=high_tree(tree);
	printf("the tree high is:%d\n",high);
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值