`
鱼吃猫
  • 浏览: 8128 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

(数据结构)遍历二叉树

阅读更多
#include <STDIO.H>
#include <STDLIB.H>

#define OK 1
#define OVERFLOW -2
#define ERROR 0

typedef int TElemType;
typedef int Status;

typedef struct BiTNode
{
	TElemType	data;
	struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;

Status CreateBiTree(BiTNode **);		//建立二叉链表
Status PreOrderTraverse( BiTNode * );		//前序遍历
Status InOrderTraverse( BiTNode * );		//中序遍历
Status PostOrderTraverse( BiTNode * );		//后序遍历
Status PrintElement(TElemType);

int main()
{
	BiTNode * T = NULL;
	CreateBiTree( &T );
	PreOrderTraverse( T );
	printf("\n");
	InOrderTraverse( T );
	printf("\n");
	PostOrderTraverse( T );
	printf("\n");
	return 0;
}

Status CreateBiTree( BiTNode ** T )
{
	char ch;
	scanf("%c" , &ch);
	if (ch == '#')
		(*T) = 0;
	else 
	{
		if ( !( (*T) = (BiTNode * ) malloc (sizeof ( BiTNode )) )) exit(OVERFLOW);
		(*T)->data = ch;
		CreateBiTree( &((*T)->lchild ));
		CreateBiTree( &((*T)->rchild ));
	}
	
	return OK;
}

Status PreOrderTraverse( BiTNode * T)
{
	if ( T )
	{
		if (PrintElement( T->data ))
			if(	PreOrderTraverse( T->lchild ))
				if( PreOrderTraverse( T->rchild ))
					return OK;
				return ERROR;
	}
	else
		return OK;
	
}

Status InOrderTraverse( BiTNode * T)
{
	if ( T )
	{
		if ( InOrderTraverse( T->lchild ))
			if(	PrintElement( T->data ))
				if( InOrderTraverse( T->rchild ))
					return OK;
				return ERROR;
	}
	else
		return OK;	
}

Status PostOrderTraverse( BiTNode * T)
{
	if ( T )
	{
		if ( PostOrderTraverse( T->lchild ))
			if(	PostOrderTraverse( T->rchild ))
				if( PrintElement( T->data ))
					return OK;
				return ERROR;
	}
	else
		return OK;	
}

Status PrintElement( TElemType e)
{
	printf("%c" , e);
	return OK;
}


比如建立下图所示的二叉树,则输入为:-+A##*B##-C##D##/E##F##

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics