6-9 二叉树的遍历 (25 分)
本题要求给定二叉树的4种遍历。
函数接口定义:
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
其中BinTree
结构定义如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
要求4个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(); /* 实现细节忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
int main()
{
BinTree BT = CreatBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
printf("Levelorder:"); LevelorderTraversal(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
Levelorder: A B C D F G I E H
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 using namespace std; 5 6 typedef char ElementType; 7 typedef struct TNode *Position; 8 typedef Position BinTree; 9 struct TNode{ 10 ElementType Data; 11 BinTree Left; 12 BinTree Right; 13 }; 14 15 BinTree CreatBinTree(); /* 实现细节忽略 */ 16 void InorderTraversal( BinTree BT );//中序遍历 17 void PreorderTraversal( BinTree BT );//前序遍历 18 void PostorderTraversal( BinTree BT );//后序遍历 19 void LevelorderTraversal( BinTree BT );//层序遍历 20 21 int main() 22 { 23 BinTree BT = CreatBinTree(); 24 printf("Inorder:"); InorderTraversal(BT); printf("\n"); 25 printf("Preorder:"); PreorderTraversal(BT); printf("\n"); 26 printf("Postorder:"); PostorderTraversal(BT); printf("\n"); 27 printf("Levelorder:"); LevelorderTraversal(BT); printf("\n"); 28 return 0; 29 } 30 31 void InorderTraversal(BinTree BT){ 32 //中序遍历 33 if(BT){ 34 InorderTraversal(BT->Left); 35 cout << " " << BT->Data; 36 InorderTraversal(BT->Right); 37 } 38 } 39 void PreorderTraversal(BinTree BT){ 40 //前序遍历 41 if(BT){ 42 cout << " " << BT->Data; 43 PreorderTraversal(BT->Left); 44 PreorderTraversal(BT->Right); 45 } 46 } 47 void PostorderTraversal(BinTree BT){ 48 //后序遍历 49 if(BT){ 50 PostorderTraversal(BT->Left); 51 PostorderTraversal(BT->Left); 52 cout << " " << BT->Data; 53 } 54 } 55 void LevelorderTraversal(BinTree BT){ 56 //层次遍历 57 BinTree p; 58 BinTree q[55];//指针数组 59 int f = 0, r = 0; 60 if(BT){//首先判断该树是否为空树 61 q[r++] = BT;//从此处开始形成队列 62 while(f != r){ 63 p = q[f++]; 64 cout << " " << p->Data; 65 if(p->Left != NULL){ 66 q[r++] = p->Left; 67 } 68 if(p->Right != NULL){ 69 q[r++] = p->Right; 70 } 71 } 72 73 } 74 }