【PTA】6-9 二叉树的遍历 (非递归)(25分)
函数接口定义:
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个函数分别按照访问顺序打印出结点的内容,格式为一个空格跟着一个字符。
裁判测试程序样例:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef char ElementType; 5 typedef struct TNode *Position; 6 typedef Position BinTree; 7 struct TNode{ 8 ElementType Data; 9 BinTree Left; 10 BinTree Right; 11 }; 12 13 BinTree CreatBinTree(); /* 实现细节忽略 */ 14 void InorderTraversal( BinTree BT ); 15 void PreorderTraversal( BinTree BT ); 16 void PostorderTraversal( BinTree BT ); 17 void LevelorderTraversal( BinTree BT ); 18 19 int main() 20 { 21 BinTree BT = CreatBinTree(); 22 printf("Inorder:"); InorderTraversal(BT); printf(" "); 23 printf("Preorder:"); PreorderTraversal(BT); printf(" "); 24 printf("Postorder:"); PostorderTraversal(BT); printf(" "); 25 printf("Levelorder:"); LevelorderTraversal(BT); printf(" "); 26 return 0; 27 } 28 /* 你的代码将被嵌在这里 */
输出样例:
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 #define MAXSIZE 20 2 void InorderTraversal( BinTree BT ){ 3 if(BT!=NULL){ 4 BinTree stack[30]; 5 int top=-1; 6 while(BT||top!=-1){ 7 while(BT){ 8 stack[++top]=BT; 9 BT=BT->Left; 10 } 11 if(top!=-1){ 12 BT=stack[top--]; 13 printf(" %c",BT->Data); 14 BT=BT->Right; 15 } 16 } 17 } 18 } 19 void PreorderTraversal( BinTree BT ){ 20 if(BT!=NULL){ 21 BinTree stack[30]; 22 int top=-1; 23 while(BT||top!=-1){ 24 while(BT){ 25 printf(" %c",BT->Data); 26 stack[++top]=BT; 27 BT=BT->Left; 28 } 29 if(top!=-1){ 30 BT=stack[top--]; 31 BT=BT->Right; 32 } 33 } 34 } 35 } 36 void PostorderTraversal( BinTree BT ){ 37 if(BT!=NULL){ 38 BinTree pre = BT;BinTree stack[30]={NULL,NULL};int top=-1; 39 //stack[++top]=BT; 40 //BT=BT->Left; 41 while(top!=-1||BT){ 42 while(BT&&(pre!=BT->Left&&pre!=BT->Right)){ 43 stack[++top]=BT; 44 BT=BT->Left; 45 } 46 BT=stack[top]; 47 if(BT->Right!=NULL&&pre!=BT->Right){BT=BT->Right;}else{ 48 printf(" %c",BT->Data); //访问到最后的右子树的结点后,退栈。 49 pre=BT; 50 BT=stack[--top]; 51 } 52 } 53 } 54 } 55 void LevelorderTraversal( BinTree BT ){ 56 BinTree *que,t; 57 que=(BinTree*)malloc(MAXSIZE*sizeof(struct TNode *)); 58 int head=0,rear=0; 59 if(BT){ 60 que[rear]=BT;rear=(rear+1)%MAXSIZE; 61 while(head!=rear){ 62 t=que[head];head=(head+1)%MAXSIZE; 63 printf(" %c",t->Data); 64 if(t->Left) 65 { 66 que[rear]=t->Left;rear=(rear+1)%MAXSIZE; 67 } 68 if(t->Right) 69 { 70 que[rear]=t->Right;rear=(rear+1)%MAXSIZE; 71 } 72 } 73 } 74 }