4月21号作业

本文介绍了如何使用C语言实现二叉树的先序、中序和后序遍历算法,以及链式队列的创建、判空、入队、出队和输出功能。
摘要由CSDN通过智能技术生成

思维导图

2 二叉树中序,和后序遍历

#include "dtee.h"
//创建结点
tree_p create_node(char data)
{
	tree_p now = (tree_p)malloc(sizeof(node));
	if(now==NULL)
	{
		printf("空间申请失败\n");
		return NULL;

	}
	now->data = data;
	return now;
}	
//2、创建二叉树,二叉树结点的数据由终端输入完成,当输入#表示无需创建结点
tree_p create_tree()
{
	char data = '\0';
	scanf(" %c",&data);
	if(data=='#')
	{
		return NULL;
	}
	tree_p T = create_node(data);  //给数据申请结点
	T->lchild = create_tree();  //根节点的左子树仍然是一颗二叉树
	T->rchild = create_tree();
	return T;
}
//3、先序遍历
void pre_show(tree_p T)
{
	if(T==NULL)
	{
		return;
	}
	//根左右
	printf("%c\n",T->data);  //输出根节点的数据
	pre_show(T->lchild);   //先序遍历左子树
	pre_show(T->rchild);   //先序遍历右子树
}
//4、中序遍历
void mid_show(tree_p T)
{
	if(T==NULL)
	{
		return;
	}
	//左根右
	mid_show(T->lchild);    //先遍历左字树
	printf("%c\n",T->data); //在遍历根
	mid_show(T->rchild);    //在遍历右字树
}
//5、后序遍历
void last_show(tree_p T)
{
	if(T==NULL)
	{
		return;
	}
	//左右根
	last_show(T->lchild); //先遍历左字树
	last_show(T->rchild); //在遍历右字树
	printf("%c\n",T->data);//在遍历根;
}

3,链式队列

#include "link_queue.h"
//创建链式队列
node_p create_link_queue()  
{
	node_p T=(Tnode_p)malloc(sizeof(node));
	if(T==NULL)
	{
		printf("空间申请失败\n");
		return NULL;
	}
	T->front=NULL;
	T->rear=NULL;
	return T;
}
//创建结点
node_p create_node(int data)  
	node_p new=(node_p)malloc(sizeof(node));
	if(new==NULL)
	{
		printf("创建结点失败\n");
		return NULL;
	}
	new->data=data;
	return new;
}
//判空
int empty_link_queue(node_p T) 
{
	if(T==NULL)
	{
		printf("入参为空,请检查\n");
		return -1;
	}
	return T->front==NULL && T->rear==NULL;
}
//入队
void push_link_queue(node_p T,int data) 
	if(T==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	node_p new=create_node(data);
	if(T->front==NULL)
	{
		new->next=T->front;
		T->front=new;
		T->rear=new;
	}
	else
	{
		new->next=T->rear->next;
		T->rear->next=new;
		T->rear=new;
	}
	printf("入队元素为%d\n",new->data);
}
//出队
void pop_link_queue(node_p T)  
{
	if(T==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if(empty_link_queue(T))
	{
		printf("队列为空,无需出队\n");
		return;
	}
	printf("出队的元素为%d\n",T->front->data);
	node_p del=T->front;
	T->front=del->next;
	free(del);
}
//输出
void show_link_queue(node_p T)  
	if(T==NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if(empty_link_queue(T))
	{
		printf("队列为空,无需输出\n");
		return;
	}
	node_p p=T->front;
	while(p!=NULL)
	{
		printf("%-4d",p->data);
		p=p->next;
	}
	putchar(10);
}

4,画出图中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值