#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);
}
}
数据结构-3 二叉树的遍历
最新推荐文章于 2022-11-03 10:15:00 发布