資料結構-3 二叉樹的遍歷
阿新 • • 發佈:2018-12-26
#include<stdio.h>
typedef int ElementType;
// 二叉樹鏈式儲存的資料結構
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode {
ElementType Data;
BinTree Left;
BinTree Right;
};
// 前序遍歷的遞迴實現
void PreorderTraversal1(BinTree BT) {
if (BT) {
printf("%d", BT->Data);
PreorderTraversal(BT-> Left);
PreorderTraversal(BT->Right);
}
}
// 前序遍歷的堆疊實現
void PreorderTraversal2(BinTree BT) {
BinTree T = BT;
Stack S = CreateStack(MaxSize);
while (T || !isEmpty(S)) {
while (T) {
Push(S, T);
printf("%d", T->Data);
T = T->Left;
}
if (!isEmpty(S)) {
T = Pop(S);
T = T->Right;
}
}
}
// 中序遍歷的遞迴實現
void InorderTraversal1(BinTree BT) {
if (BT) {
PreorderTraversal(BT->Left);
printf("%d", BT->Data);
PreorderTraversal(BT->Right);
}
}
// 中序遍歷的堆疊實現
void InorderTraversal2(BinTree BT) {
BinTree T = BT;
Stack S = CreateStack(MaxSize);
while (T || !isEmpty(S)) {
while (T) {
Push(S, T);
T = T->Left;
}
if (!isEmpty(S)) {
T = Pop(S);
printf("%d", T->Data);
T = T->Right;
}
}
}
// 後序遍歷的遞迴實現
void PostorderTraversal1(BinTree BT) {
if (BT) {
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
printf("%d", BT->Data);
}
}
// 後序遍歷的堆疊實現
// 層次遍歷的佇列實現
void LevelorderTraversal(BinTree BT) {
BinTree TP;
if (!BT) return;
Queue Q = CreateQueue();
AddQuene(Q, BT); // 將根節點入隊
while (isEmpty(Q)) {
TP = DeleteQueue(Q);
printf("%d ", TP->Data);
if (TP->Left) AddQuene(Q, TP->Left);
if (TP->Right) AddQuene(Q, TP->Right);
}
}