2024/02/07

1请编程实现二又树的操作
1.1二又树的创建
1.2二又树的先序遍历
1.3二又树的中序遍历
1.4二又树的后序遍历
1.5二又树各个节点度的个数
1.6二叉树的深度

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(NULL==s)
		return NULL;
	//初始化
	s->data='\0';
	s->lchild=s->rchild=NULL;
}
//创建二叉树
Btree create_tree()
{
	datatype element;//插入的数据域
	printf("please enter element:");
	scanf(" %c",&element);
	if(element=='#')
		return NULL;
	//创建节点
	Btree tree=create_node();
	tree->data=element;
	//递归创建左孩子
	printf("%c_lchild:\n",element);
//	puts("lchild");
	tree->lchild=create_tree();
	//递归创建右孩子
	printf("%c_rchild:\n",element);
//	puts("rchild");
	tree->rchild=create_tree();
	return tree;
}

//先序遍历二叉树
void first(Btree tree)
{
	if(tree==NULL)
		return;
	//遍历根节点
	printf("%c",tree->data);
	//递归遍历左孩子
	first(tree->lchild);
	//递归遍历右孩子
	first(tree->rchild);
}

//中序遍历二叉树
void mid(Btree tree)
{
	if(tree==NULL)
		return;
	//递归遍历左孩子
	mid(tree->lchild);
	//遍历根节点
	printf("%c",tree->data);
	//递归遍历右孩子
	mid(tree->rchild);
}

//后序遍历二叉树
void rear(Btree tree)
{
	if(tree==NULL)
		return;
	//递归遍历左孩子
	rear(tree->lchild);
	//递归遍历右孩子
	rear(tree->rchild);
	//遍历根节点
	printf("%c",tree->data);
}

//计算各度数节点和
void Count(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->lchild,n0,n1,n2);
	//递归遍历右孩子
	Count(tree->rchild,n0,n1,n2);
}

//计算二叉树深度
int high(Btree tree)
{
	if(tree==NULL)
		return 0;
	//递归计算左子树深度
	int left=1+high(tree->lchild);
	//递归计算右子树深度
	int right=1+high(tree->rchild);
	//返回左右最大深度
	return left>right?left:right;
 	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值