二叉树遍历
1 #include<stdio.h> 2 3 typedef struct Tree{ 4 char data; 5 struct Tree* left; 6 struct Tree* right; 7 }Tree; 8 9 void pre_travel(Tree* ptree){ 10 if(ptree){ 11 printf("%c",ptree->data); 12 if(ptree->left) 13 pre_travel(ptree->left); 14 if(ptree->right) 15 pre_travel(ptree->right); 16 } 17 } 18 19 void in_travel(Tree* ptree){ 20 if(ptree){ 21 if(ptree->left) 22 pre_travel(ptree->left); 23 printf("%c",ptree->data); 24 if(ptree->right) 25 pre_travel(ptree->right); 26 } 27 28 } 29 30 void post_travel(Tree* ptree){ 31 if(ptree){ 32 if(ptree->left) 33 pre_travel(ptree->left); 34 if(ptree->right) 35 pre_travel(ptree->right); 36 printf("%c",ptree->data); 37 } 38 39 }; 40 41 int main(){ 42 Tree tree[5]; 43 int i=0; 44 for(i=0;i<5;i++){ 45 tree[i].data='A'+i; 46 } 47 tree[0].left=&tree[1]; 48 tree[0].right=&tree[2]; 49 tree[1].left=&tree[3]; 50 tree[1].right=&tree[4]; 51 for(i=2;i<5;i++){ 52 tree[i].left=NULL; 53 tree[i].right=NULL; 54 } 55 printf("pre_order\n"); 56 pre_travel(&tree[0]); 57 printf("in_order\n"); 58 in_travel(&tree[0]); 59 printf("post_order\n"); 60 post_travel(&tree[0]); 61 return 0; 62 }