c语言——树的遍历

  最近学习了树和二叉树的知识,所以今天写了一个关于树的创建和遍历的代码。树的三种遍历方式,分别是,先序遍历:根左右,中序遍历:左根右,后序遍历:左右根。然后需要创建链表,存放根结点和左右孩子。

递归遍历:

#include<stdio.h>
#include<stdlib.h>
struct bitnode
{
	char Date;//根结点
	struct bitnode* Lchild;//左子树
	struct bitnode* Rchild;//右子树
};
//创建二叉树
bitnode* createtree(bitnode* t)
{
	char ch;
	printf("请输入结点:");
	scanf("%c", &ch);
	getchar();
	if (ch == '#')
	{
		t = NULL;
	}
	else
	{
		//递归创建结点并赋值
		t = (bitnode*)malloc(sizeof(bitnode));
		t->Date = ch;
		t->Lchild = createtree(t->Lchild);
		t->Rchild = createtree(t->Rchild);
	}
	return t;
}
//先序遍历
void preorder(bitnode* t)
{
	if (t!= NULL)
	{
		//根左右
		printf("%c ", t->Date);
		preorder(t->Lchild);
		preorder(t->Rchild);
	}
}
//中序遍历
void inorder(bitnode* t)
{
	if (t != NULL)
	{
		//左根右
		inorder(t->Lchild);
		printf("%c ", t->Date);
		inorder(t->Rchild);
	}
}
//后序遍历
void postorder(bitnode* t)
{
	if (t != NULL)
	{
		//左右根
		postorder(t->Lchild);
		postorder(t->Rchild);
		printf("%c ", t->Date);
	}
}
int main()
{
	bitnode* t=(bitnode*)malloc(sizeof(bitnode));
	//创建一个初始二叉树
	t = createtree(t); 

	//先序
	printf("先序遍历为:");
	preorder(t);
	printf("\n");

	//中序
	printf("中序遍历为:");
	inorder(t);
	printf("\n");

	//后序
	printf("后序遍历为:");
	postorder(t);
	printf("\n");
	return 0;
}

以上便是树的三种递归遍历的写法

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

梦一诚

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

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值