SDUT 2128 树结构练习——排序二叉树的中序遍历

题目链接

目测二叉堆就是用的排序二叉树。然后还恶搞一下AC代码。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <stdlib.h>

 4 int num[1001];

 5 int n,z;

 6 struct tree

 7 {

 8     int data;

 9     struct tree *left;

10     struct tree *right;

11 };

12 struct tree *build()

13 {

14     struct tree *p;

15     p = (struct tree *)malloc(sizeof(struct tree));

16     p -> data = num[1];

17     p -> left = NULL;

18     p ->right = NULL;

19     return p;

20 }

21 void search(struct tree *head,int x)

22 {

23     struct tree *p;

24     if(head -> data > x)

25     {

26         if(head -> left != NULL)

27             search(head -> left,x);

28         else

29         {

30             p = (struct tree *)malloc(sizeof(struct tree));

31             p -> data = x;

32             p -> left = NULL;

33             p ->right = NULL;

34             head ->left = p;

35         }

36     }

37     else

38     {

39         if(head -> right != NULL)

40             search(head -> right,x);

41         else

42         {

43             p = (struct tree *)malloc(sizeof(struct tree));

44             p -> data = x;

45             p -> left = NULL;

46             p ->right = NULL;

47             head -> right = p;

48         }

49     }

50 }

51 void midshow(struct tree *k)

52 {

53     if(k)

54     {

55         midshow(k -> left);

56         if(z)

57         {

58             printf("%d",k -> data);

59             z = 0;

60         }

61         else

62             printf(" %d",k ->data);

63         midshow(k -> right);

64     }

65     else

66         return ;

67 }

68 int main()

69 {

70     int i;

71     struct tree *head;

72     while(scanf("%d",&n)!=EOF)

73     {

74         z = 1;

75         for(i = 1; i <= n; i ++)

76         {

77             scanf("%d",&num[i]);

78             if(i == 1)

79                 head = build();

80             else

81                 search(head,num[i]);

82         }

83         midshow(head);

84         printf("\n");

85     }

86     return 0;

87 }

恶搞版

 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 int p[1001];

 4 int cmp(const void *a,const void *b)

 5 {

 6     return *(int *)a - *(int *)b;

 7 }

 8 int main()

 9 {

10     int n,i;

11     while(scanf("%d",&n)!=EOF)

12     {

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

14             scanf("%d",&p[i]);

15         qsort(p,n,sizeof(p[0]),cmp);

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

17         {

18             if(i == 0)

19                 printf("%d",p[i]);

20             else

21                 printf(" %d",p[i]);

22         }

23         printf("\n");

24     }

25     return 0;

26 }

你可能感兴趣的:(二叉树)