二叉链表的遍历

晚上闲着没事请干,敲敲书上的二叉树,用递归的方法实现最简单的前序,中序,后序遍历

Tree.h

//BiTree 
#include 
#include 

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

//typedef
typedef int Status;
typedef char TElemType;

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

//functions
Status CreateBiTree(BiTree &T);

Status PreOrderTraverse  (BiTree T, Status (* Visit)(TElemType e));

Status InOrderTraverse   (BiTree T, Status (* Visit)(TElemType e));

Status PostOrderTraverse (BiTree T, Status (* Visit)(TElemType e));

Status LeverOrderTraverse(BiTree T, Status (* Visit)(TElemType e));

Status Visit(TElemType e);


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


Status PreOrderTraverse  (BiTree T, Status (* Visit)(TElemType e))
{
	if (T)
	{
		Visit(T->data);
		PreOrderTraverse(T->lchild, Visit);
		PreOrderTraverse(T->rchild, Visit);
	}
	return OK;
}

Status InOrderTraverse  (BiTree T, Status (* Visit)(TElemType e))
{
	if (T)
	{
		InOrderTraverse(T->lchild, Visit);
		Visit(T->data);
		InOrderTraverse(T->rchild, Visit);
	}
	return OK;
}

Status PostOrderTraverse  (BiTree T, Status (* Visit)(TElemType e))
{
	if (T)
	{
		PostOrderTraverse(T->lchild, Visit);
		PostOrderTraverse(T->rchild, Visit);
		Visit(T->data);
	}
	return OK;
}

Status Visit(TElemType e)
{
	printf("%c\n", e);
	return OK;
}


Tree.cpp
#include "Tree.h"

int main()
{
	BiTree T;
	CreateBiTree(T);
//PreOrder 
	printf("PreOrder is\n");
	PreOrderTraverse(T, Visit);
//InOrder 
	printf("InOrder is\n");
	InOrderTraverse(T, Visit);
//PostOrder
	printf("PostOrder is\n");
	PostOrderTraverse(T, Visit);

	return 0;
}


你可能感兴趣的:(数据结构)