二叉树递归遍历

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 typedef struct TNode *position;
 4 typedef position BinTree;//二叉树类型 
 5 struct TNode{//树结点定义 
 6     char data;//指向数据 
 7     BinTree Left;
 8     BinTree Right;
 9 }; 
10 //将创建的二叉树以BinTree形式返回 
11 BinTree CreateBintree()
12 {   
13     char ch = 0;
14     BinTree BT;//等价于TNode *BT=NULL;
15     scanf("%c",&ch);
16     if('#'==ch){
17         BT=NULL;
18     }else{
19         BT=(TNode*)malloc(sizeof(TNode));//申请新的结点内存 
20         BT->data=ch;
21         BT->Left=CreateBintree();
22         BT->Right=CreateBintree();
23     }
24     return BT;
25 } 
26 //先序 (根左右) 
27 int PreOrderTravel(BinTree BT){
28     if(BT!=NULL){
29         printf("%5c",BT->data);
30         PreOrderTravel(BT->Left);
31         PreOrderTravel(BT->Right);    
32     }
33     return 0;
34 }
35 //中序(左根右) 
36 int MiddleOrderTravel(BinTree BT){
37     if(BT!=NULL){
38         MiddleOrderTravel(BT->Left);
39         printf("%5c",BT->data);
40         MiddleOrderTravel(BT->Right);    
41     }
42     return 0;
43 }
44 //后序 (左右根) 
45 int AfterOrderTravel(BinTree BT){
46     if(BT!=NULL){
47         AfterOrderTravel(BT->Left);
48         AfterOrderTravel(BT->Right);
49         printf("%5c",BT->data);    
50     }
51     return 0;
52 }
53 
54 int main(){
55    BinTree newBT;
56    newBT=CreateBintree();
57    PreOrderTravel(newBT);
58    /*之前一直有错是因newBT是空的,采取返回值保证newBT中有值*/ 
59    printf("\n");
60    MiddleOrderTravel(newBT);
61    printf("\n");
62    AfterOrderTravel(newBT);
63    return 0; 
64 }       

以此图为例

 

posted @ 2018-07-06 17:28  Freeloop_嘉  阅读(265)  评论(0编辑  收藏  举报