c语言——树的遍历

时间:2025-03-26 12:39:47

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

递归遍历:

#include<>
#include<>
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;
}

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