1. 程式人生 > >資料結構--遍歷二叉樹

資料結構--遍歷二叉樹

遍歷二叉樹

#include "pch.h"
#include <iostream>
#include <queue>
#include <stdlib.h>

#define MAX_TREE_SIZE 100
#define OK 1
#define ERROR -1

using namespace std;
typedef char Status;
typedef int TElemType;
typedef TElemType SqBiTree[MAX_TREE_SIZE];

SqBiTree bt;

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

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

}
//先序遍歷二叉樹
Status PreOrderTraverse(BiTree T, Status(*Visit)(TElemType)) {
	if (T) {
		if (Visit(T->data))
			if (PreOrderTraverse(T->lchild, Visit))
				if (PreOrderTraverse(T->rchild, Visit)) return OK;
		return ERROR;
	}
	else return OK;
}
//輸出函式
Status PrintElement(TElemType e) {
	printf("%c", e);
	return OK;
}
//中序遍歷
Status InOrderTraverse(BiTree T, Status(*Visit)(TElemType)) {
	if (T) {
		if (InOrderTraverse(T->lchild, Visit))
			if (Visit(T->data))
				if (InOrderTraverse(T->rchild, Visit)) return OK;
		return ERROR;
	}
	else return OK;
}

//後序遍歷
Status PostOrderTraverse(BiTree T, Status(*Visit)(TElemType)) {
	if (T) {

		if (PostOrderTraverse(T->lchild, Visit))
			if (PostOrderTraverse(T->rchild, Visit))
				if (Visit(T->data))
					return OK;
		return ERROR;
	}
	else return OK;
}

//層次遍歷二叉樹
void LevelOrder(BiTree T) {
	BiTree p = T;
	//佇列
	queue<BiTree> queue;
	//根節點入隊
	queue.push(T);
	//佇列不空迴圈
	while (!queue.empty()) {
		//對頭元素出隊
		p = queue.front();
		//訪問p指向的結點
		printf("%c ", p->data);
		//退出佇列
		queue.pop();
		//左子樹不空,將左子樹入隊
		if (p->lchild != NULL) {
			queue.push(p->lchild);
		}
		//右子樹不空,將右子樹入隊
		if (p->rchild != NULL) {
			queue.push(p->rchild);
		}
	}
}


int main()
{
	BiTree T;
	printf("請輸入二叉樹的元素:\n");
	CreateBiTree(T); //建立一個二叉樹
	printf("先序遍歷\n");
	PreOrderTraverse(T, PrintElement); //先序遍歷.
	printf("\n");
	printf("中序遍歷\n");
	InOrderTraverse(T, PrintElement);//中序遍歷
	printf("\n");
	printf("後序遍歷\n");
	PostOrderTraverse(T, PrintElement);//後序遍歷
	printf("\n");
	LevelOrder(T);
}