1-7 二叉树的非递归遍历
分数 5
作者 陈越
单位 浙江大学
本题要求用非递归的方法实现对给定二叉树的 3 种遍历。
函数接口定义:
void InorderTraversal( BinTree BT ); void PreorderTraversal( BinTree BT ); void PostorderTraversal( BinTree BT );
|
其中BinTree结构定义如下:
typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; int flag; };
|
要求 3 个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
此外,裁判程序中给出了堆栈的全套操作,可以直接调用。
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> typedef enum { false, true } bool;
typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; int flag; };
typedef Position SElementType; typedef struct SNode *PtrToSNode; struct SNode { SElementType Data; PtrToSNode Next; }; typedef PtrToSNode Stack;
Stack CreateStack(); bool IsEmpty( Stack S ); bool Push( Stack S, SElementType X ); SElementType Pop( Stack S ); SElementType Peek( Stack S );
BinTree CreateBinTree(); void InorderTraversal( BinTree BT ); void PreorderTraversal( BinTree BT ); void PostorderTraversal( BinTree BT );
int main() { BinTree BT = CreateBinTree(); printf("Inorder:"); InorderTraversal(BT); printf("\n"); printf("Preorder:"); PreorderTraversal(BT); printf("\n"); printf("Postorder:"); PostorderTraversal(BT); printf("\n"); return 0; }
|
输入样例:

输出样例:
Inorder: D B E F A G H C I Preorder: A B D F E C G H I Postorder: D E F B H G I C A
|
解析
void PreorderTraversal(BinTree BT) { if (BT == NULL) { return; } Stack st = CreateStack(); Push(st, BT); while (IsEmpty(st) == false){ BinTree node = Pop(st); printf(" %c", node->Data); if (node->Right) { Push(st, node->Right); } if (node->Left) { Push(st, node->Left); } } } void InorderTraversal(BinTree BT) { if (BT == NULL) { return; } Stack st = CreateStack(); BinTree current = BT; while (current != NULL || !IsEmpty(st)) { while (current != NULL) { Push(st, current); current = current->Left; } if (!IsEmpty(st)) { current = Pop(st); printf(" %c", current->Data); current = current->Right; } } } void PostorderTraversal(BinTree BT) { if (BT == NULL) return; Stack st = CreateStack(); Push(st, BT); BT->flag = 0; while (!IsEmpty(st)) { BinTree node = Peek(st); if (node->flag == 0) { node->flag = 1; if (node->Right) { node->Right->flag = 0; Push(st, node->Right); } if (node->Left) { node->Left->flag = 0; Push(st, node->Left); } } else { node = Pop(st); printf(" %c", node->Data); } } }
|