数据结构总结7——树——二叉树的递归遍历 by DexterYan

一、基础知识

二、代码要求

5.1二叉树的递归遍历
利用二叉链表实现二叉树的存储, 先序递归遍历创建(已知的)二叉树、中序及后序递归遍历输出该二叉树(2学时)

三、代码实现

#include<stdio.h>
#include<stdlib.h> 
#define N 100
typedef struct node
{
	char data;
	struct node *lchild,*rchild;
}BTNode;
/*---二叉树的建立---*/
BTNode *createbintree()
{
	BTNode *t;
	char x;
	scanf("%c",&x);
	if (x=='#')
		t=NULL;
	else
	{
		t=(BTNode *)malloc(sizeof(BTNode));
		t->data=x;
	t->lchild=createbintree();
	t->rchild=createbintree();
	}
	return(t);
}
/*---先序遍历算法---*/
void preorder(BTNode *t)
{
	if(t!=NULL)
	{
		printf("%c ",t->data);
		preorder(t->lchild);
		preorder(t->rchild);
	}
}

/*---中序遍历算法(递归算法)---*/
void inorder(BTNode *t)
{
	if(t!=NULL)
	{
		inorder(t->lchild);
		printf("%c ",t->data);
		inorder(t->rchild);
	}
}

/*---后序遍历算法---*/
void postorder(BTNode *t)
{
	if(t!=NULL)
	{
		postorder(t->lchild);
		postorder(t->rchild);
		printf("%c ",t->data);
	}
}

int main()
{
	BTNode *t;
	printf("请按先序遍历输入树(#表示结点为空):\n");
	t=createbintree();
	printf("先序遍历输出:");
	preorder(t);
	printf("\n");
	printf("中序遍历输出:");
	inorder(t);
	printf("\n");
	printf("后序遍历输出:");
	postorder(t);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41259302/article/details/90522992
今日推荐