3341=数据结构实验之二叉树二:遍历二叉树

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 char s[100];
 4 int b;//b用来统计输入的字符串遍历到哪里了。
 5 struct node
 6 {
 7     struct node*left,*right;
 8     char c;//定义一颗二叉树。
 9 };
10 struct node *creat()
11 {
12      struct node *root;
13      char t;
14      t=s[b++];
15      if(t==',')return NULL;
16      else
17      {
18          root=(struct node*)malloc(sizeof(struct node));
19          root->c=t;
20          root->left=creat();
21          root->right=creat();
22      }
23      return root;//返回根节点。
24      //因为是先序遍历,所以从左节点开始。
25 };
26 void mid(struct node*root)
27 {
28     if(root)
29     {
30         mid(root->left);
31         printf("%c",root->c);
32         mid(root->right);
33     }
34 }
35 void end(struct node*root)
36 {
37     if(root)
38     {
39         end(root->left);
40         end(root->right);
41         printf("%c",root->c);
42     }
43 }
44 int main()
45 {
46     struct node *root;
47     while(scanf("%s",s)!=EOF)
48     {
49         b=0;
50         root=(struct node*)malloc(sizeof(struct node));
51         root=creat();
52         mid(root);
53         printf("\n");
54         end(root);
55         printf("\n");
56     }
57     return 0;
58 }

猜你喜欢

转载自www.cnblogs.com/Angfe/p/10427181.html