算法-二叉树的遍历


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 
#include 

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 void InorderTraversal( BinTree BT )
 2 {
 3     if(BT){ InorderTraversal(BT->Left);
 4     printf(" %c",BT->Data);
 5     InorderTraversal(BT->Right);}
 6 }
 7 void PreorderTraversal( BinTree BT ){
 8     if(BT){
 9         printf(" %c",BT->Data);
10         PreorderTraversal(BT->Left);
11         PreorderTraversal(BT->Right);
12     }
13 }
14 void PostorderTraversal( BinTree BT ){
15     if(BT){
16         PostorderTraversal(BT->Left);
17         PostorderTraversal(BT->Right);
18         printf(" %c",BT->Data);
19     }
20 }
21 void LevelorderTraversal( BinTree BT ){
22     BinTree l[100];//建立队列
23     BinTree temp = BT;//使用temp作为当前结点实现遍历
24     int head = 0;
25     int rare = 0;
26     if(BT){
27         l[rare++] = temp;//先将树根存进去 
28         while(rare-head>0)
29             {temp = l[head++];
30         printf(" %c",temp->Data);
31         if(temp->Left)
32             l[rare++] = temp->Left;
33         if(temp->Right)
34             l[rare++] = temp->Right;}//使节点按顺序进入队列
35     }
36 }

相关