数据结构输出先序遍历、中序遍历、后序遍历

了解遍历

了解遍历

题目:

已知二叉树的先序遍历为:A B D E G C F

                     中序遍历为:D B G E A C F

                  则后序遍历为:

画图分析

 

二叉树遍历的代码(递归算法)

typedef:为了给用户自定义的数据类型取一个新的名字

#include <stdio.h>
#include <stdlib.h>
typedef char DataType;

typedef struct Node
{
	DataType data;
	struct Node * LChild;
	struct Node * RChild;
}BiTNode,* BiTree;

//创建
void CreateNode (BiTree *T)
{
	DataType ch;
	scanf("%c",&ch);
	if(ch=='#')
        *T=NULL;
	else{
		*T=(BiTree) malloc (sizeof(Node ));
		 
		(*T)->data=ch;
		CreateNode(&(*T)->LChild);
		CreateNode(&(*T)->RChild);
		
	}
}

//输出
void Ch(DataType ch)
{
	printf(" %c ",ch);
}
//先序遍历二叉树
void PreOrder(BiTree T)
{
	if(T!=NULL)
	{
		Ch(T->data);
		PreOrder(T->LChild);
		PreOrder(T->RChild);
	}
}

//中序遍历
void InOrder(BiTree T)
{
	if(T!=NULL)
	{
		InOrder(T->LChild);
		Ch(T->data);
		InOrder(T->RChild);
	}
}

//后序遍历
void PostOrder(BiTree T)
{
	if(T!=NULL)
	{
		PostOrder(T->LChild);
		PostOrder(T->RChild);
		Ch(T->data);
	}
}


int main()
{
	BiTree T;
	printf("按先序遍历输入(没有孩子的输入#): \n");
	CreateNode(&T);
	printf("先序遍历: \n");
	PreOrder(T);
	printf("\n");
	printf("中序遍历: \n");
	InOrder(T);
	printf("\n");
	printf("后序遍历: \n");
	PostOrder(T);
	printf("\n");
	return 0;
}

所以

则后序遍历为:D G E B F C A

猜你喜欢

转载自blog.csdn.net/weixin_44068262/article/details/106290250