SDUT 2137 数据结构实验之求二叉树后序遍历和层次遍历

 题目链接:http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2137

  后序遍历没啥好说的,递归就好,层次遍历有点BFS的感觉。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <stdlib.h>

 4 struct tree

 5 {

 6     char l;

 7     struct tree *left,*right;

 8 };

 9 struct tree *build(char *p,char *s,int n)

10 {

11     struct tree *tail;

12     int i;

13     if(n <= 0)return NULL;

14     tail = (struct tree *)malloc(sizeof(struct tree));

15     for(i = 0;i <= n-1;i ++)

16     {

17         if(p[0] == s[i])

18         break;

19     }

20     tail ->l = p[0];

21     tail -> left = build (p+1,s,i);

22     tail -> right = build (p+i+1,s+i+1,n-i-1);

23     return tail;

24 }

25 void downshow(struct tree *k)

26 {

27     if(k)

28     {

29         downshow(k -> left);

30         downshow(k -> right);

31         printf("%c",k -> l);

32     }

33 }

34 void stepshow(struct tree *k,char *p,int n)

35 {

36     int i,j,start,end,num;

37     struct tree *point[1000];

38     start = 0;

39     end = 0;

40     num = 0;

41     point[0] = k;

42     while(start < n)

43     {

44         j = 1;

45         for(i = start;i <= end;i ++)

46         {

47             p[i] = point[i] -> l;

48             if(point[i] -> left )

49             {

50                 point[end + j] = point[i] -> left;

51                 j ++;

52             }

53             if(point[i] -> right )

54             {

55                 point[end + j] = point[i] ->right;

56                 j ++;

57             }

58         }

59         start = end + 1;

60         end = end + j - 1;

61     }

62     p[n]='\0';

63 }

64 int main()

65 {

66     char str1[1000],str2[1000],str3[1000];

67     int t,l;

68     struct tree *head;

69     scanf("%d",&t);

70     while(t--)

71     {

72         memset(str3,0,sizeof(str3));

73         scanf("%s%s",str1,str2);

74         l = strlen(str1);

75         head = build(str1,str2,l);

76         downshow(head);

77         printf("\n");

78         stepshow(head,str3,l);

79         printf("%s\n",str3);

80     }

81     return 0;

82 }

 

你可能感兴趣的:(数据结构)