数据结构与算法题目集(中文) 6-9 二叉树的遍历 (25分)

 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("\n");
23 //     printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
24 //     printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
25 //     printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
26 //     return 0;
27 // }
28 
29 //space + char
30 

//中序 31 void InorderTraversal( BinTree BT ) 32 { 33 if (BT) 34 { 35 InorderTraversal( BT->Left); 36 printf(" %c", BT->Data); 37 InorderTraversal( BT->Right); 38 } 39 40 } 41
//前序 42 void PreorderTraversal( BinTree BT ) 43 { 44 45 if (BT) 46 { 47 printf(" %c", BT->Data); 48 PreorderTraversal(BT->Left); 49 PreorderTraversal(BT->Right); 50 } 51 52 }

//后序
53 void PostorderTraversal( BinTree BT) 54 { 55 if (BT) 56 { 57 PostorderTraversal(BT->Left); 58 PostorderTraversal(BT->Right); 59 printf(" %c", BT->Data); 60 } 61 62 63 }
//层遍历 用到队列知识
64 void LevelorderTraversal( BinTree BT ) 65 { 66 67 BinTree qu[2000]; 68 int head = 0, tail = 0; 69 70 if (BT) qu[tail++] = BT; 71 72 while (head < tail) 73 { 74 if(qu[head]->Left) qu[tail++] = qu[head]->Left; 75 if(qu[head]->Right) qu[tail++] = qu[head]->Right; 76 printf(" %c",qu[head++]->Data); 77 } 78 79 80 }

猜你喜欢

转载自www.cnblogs.com/ccvv/p/12445872.html