首页 > 代码库 > 4-9 二叉树的遍历 (25分)

4-9 二叉树的遍历 (25分)

4-9 二叉树的遍历   (25分)

输出样例(对于图中给出的树):

技术分享

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 //  4-9 二叉树的遍历
 2 //
 3 //  Created by Haoyu Guo on 04/02/2017.
 4 //  Copyright ? 2017 Haoyu Guo. All rights reserved.
 5 //
 6 #include <stdio.h>
 7 #include<iostream>
 8 #include <stdlib.h>
 9 #define OVERFLOW -2
10 using namespace std;
11 typedef char ElementType;
12 typedef struct TNode *Position;
13 typedef Position BinTree;
14 struct TNode{
15     ElementType Data;
16     BinTree Left;
17     BinTree Right;
18 };
19 
20 int CreatBinTree(BinTree &T)//创建二叉树
21 {
22     char ch;//按先序的方式输入
23     cin >> ch;
24     if (ch == #)  T=NULL;
25     else {
26         if (!(T = (BinTree)malloc(sizeof(TNode)))) exit(OVERFLOW);
27         T->Data =http://www.mamicode.com/ ch;
28         CreatBinTree(T->Left);
29         CreatBinTree(T->Right);
30     }
31     return 0;
32 }
33 void InorderTraversal( BinTree BT );
34 void PreorderTraversal( BinTree BT );
35 void PostorderTraversal( BinTree BT );
36 void LevelorderTraversal( BinTree BT );
37 
38 int main()
39 {
40     BinTree BT;
41     CreatBinTree(BT);
42     printf("Inorder:");    InorderTraversal(BT);    printf("\n");
43     printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
44     printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
45     printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
46     return 0;
47 }
48 /* 你的代码将被嵌在这里 */
49 void InorderTraversal( BinTree BT )//中根遍历
50 {
51     if(BT==NULL)
52         return;
53     else
54     {
55         InorderTraversal(BT->Left);
56         printf(" %c",BT->Data);
57         InorderTraversal(BT->Right);
58     }
59 }
60 void PreorderTraversal( BinTree BT )//先序遍历
61 {
62     if(BT==NULL) return;
63     else{
64         printf(" %c",BT->Data);
65         PreorderTraversal(BT->Left);
66         PreorderTraversal(BT->Right);
67     }
68 }
69 
70 void PostorderTraversal( BinTree BT )//后序遍历
71 {
72     if(BT==NULL) return;
73     else{
74         PostorderTraversal(BT->Left);
75         PostorderTraversal(BT->Right);
76          printf(" %c",BT->Data);
77     }
78 }
79 void LevelorderTraversal( BinTree BT )//层序遍历
80 {
81     if(BT==NULL) return;
82     else{
83         BinTree q[100];
84         BinTree p;
85         int head=0,tail=0;
86         if(!BT) return;
87         if(BT){
88             q[tail++]=BT;
89             while(tail!=head){
90                 p=q[head++];
91                 printf(" %c",p->Data);
92                 if(p->Left)     q[tail++]=p->Left;
93                 if(p->Right)    q[tail++]=p->Right;
94             } 
95         }
96         
97     }
98 }

 

 

4-9 二叉树的遍历 (25分)