二叉树的递归遍历

//按照先序遍历的方法建立一颗二叉树
include<iostream>
#include<iomanip>
using namespace std;
#define OK 1
#define ERROR 0
typedef char  TElemType;
typedef int Status;
typedef struct BiTNode {
	TElemType data;
	struct BiTNode *lchild, *rchild, *parent;
}BiTNode, *BiTree;
Status PreOrderTree(BiTree T);
Status CreateBiTree(BiTree &T);//按先序次序输入二叉树中节点的值(一个字符),空格字符表示空数
Status PreOrderTraverse(BiTree T, Status(*PrintElement)(TElemType));//先序遍历
Status InOrderTraverse(BiTree T, Status(*PrintElement)(TElemType));//中序遍历
Status PostOrderTraverse(BiTree T, Status(*PrintElement)(TElemType));//后续遍历
Status PrintElement(TElemType e);
Status CreateBiTree(BiTree &T) {
	char ch = 0;
	ch = getchar();
	if (ch == '*')//*号代表节点为空
		T = NULL;
	else {
		if (!(T = (BiTree)malloc(sizeof(BiTNode))))
			exit(0);
		else {
			T->data = ch;
			CreateBiTree(T->lchild);
			CreateBiTree(T->rchild);
		}
	}
	return OK;

}

Status InOrderTraverse(BiTree T, Status(*PrintElement)(TElemType e)) {
	if (T) {
		if (InOrderTraverse(T->lchild, PrintElement))
			if (PrintElement(T->data))
				if (InOrderTraverse(T->rchild, PrintElement)) return OK;
		return ERROR;
	}
	else
		return OK;
}
Status PreOrderTraverse(BiTree T, Status(*PrintElement)(TElemType e)) {
	if (T) {
		if (PrintElement(T->data))
			if (PreOrderTraverse(T->lchild, PrintElement))
				if (PreOrderTraverse(T->rchild, PrintElement))return OK;
		return ERROR;
	}
	else
		return OK;
}
Status PostOrderTraverse(BiTree T, Status(*PrintElement)(TElemType e)) {
	if (T) {
		if (PostOrderTraverse(T->lchild, PrintElement))
			if (PostOrderTraverse(T->rchild, PrintElement))
				if (PrintElement(T->data))
					return OK;
		return ERROR;
	}
	else
		return OK;
}
Status  PrintElement(TElemType e) {
	printf("%2c", e);
	return OK;
}
int main()
{
	BiTree T;
	CreateBiTree(T);
	printf("先序遍历为:");
	PreOrderTraverse(T, PrintElement);
	printf("\n");
	printf("中序遍历是:");
	InOrderTraverse(T, PrintElement);
	printf("\n");
	printf("后续遍历是:");
	PostOrderTraverse(T, PrintElement);
	printf("\n");
	system("pause");
	return 0;
}

阅读更多
文章标签: 二叉树
个人分类: 数据结构 
上一篇线性表的基本操作
下一篇二叉树的非递归遍历(C语言实现)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭