fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5.  
  6. struct List {
  7. struct List *next;
  8. void *object;
  9. } ;
  10.  
  11.  
  12. typedef struct __queue {
  13. struct List *front;
  14. struct List *back;
  15. } *Queue;
  16.  
  17. #define init(queue) do{\
  18.   queue = malloc(sizeof(struct __queue));\
  19.   if (queue == NULL) {\
  20.   perror("initial "#queue" error: ");\
  21.   exit(EXIT_FAILURE);\
  22.   }\
  23.   queue->back = queue->front = NULL;\
  24.   }while (0)
  25.  
  26.  
  27. #define empty(queue) (queue->front == NULL)
  28.  
  29. #define front(queue) (queue->front->object)
  30.  
  31. void pop(Queue q) {
  32. void *ans;
  33. struct List *tmp;
  34.  
  35.  
  36. if (empty(q))return;
  37.  
  38. ans = q->front->object;
  39. tmp = q->front;
  40. q->front = tmp->next;
  41.  
  42. free(tmp);
  43. }
  44.  
  45. void push(Queue q,void* ob) {
  46. struct List *tmp;
  47. tmp = malloc(sizeof(struct List));
  48. if (tmp == NULL) {
  49. perror("push object error: ");
  50. return;
  51. }
  52. tmp->next = NULL;
  53. tmp->object = ob;
  54. if (!empty(q))
  55. q->back->next = tmp;
  56. else
  57. q->front = tmp;
  58.  
  59. q->back = tmp;
  60. }
  61.  
  62.  
  63. typedef struct __tree{
  64. struct __tree *left;
  65. struct __tree *right;
  66. int num;
  67. } *Tree;
  68.  
  69. void dfs_print(Tree t) {
  70. printf("%d ",t->num);
  71.  
  72. if (t->left != NULL)
  73. dfs_print(t->left);
  74.  
  75. if (t->right != NULL)
  76. dfs_print(t->right);
  77. }
  78.  
  79. int main(void) {
  80. int num,flag_r,flag_l;
  81. Queue qu;
  82. Tree T = NULL,*tmp;
  83.  
  84. init(qu);
  85. push(qu,&T);
  86.  
  87. while (!empty(qu)) {
  88. tmp = front(qu);
  89. pop(qu);
  90.  
  91. *tmp = malloc(sizeof(struct __tree));
  92. if (*tmp == NULL) {
  93. perror("add new node error: ");
  94. continue;
  95. }
  96.  
  97. scanf("%d%d%d",&num,&flag_l,&flag_r);
  98.  
  99. (*tmp)->left = NULL;
  100. if (flag_l)
  101. push(qu,&(*tmp)->left);
  102.  
  103. (*tmp)->right = NULL;
  104. if (flag_r)
  105. push(qu,&(*tmp)->right);
  106.  
  107. (*tmp)->num = num;
  108. }
  109. dfs_print(T);
  110. putchar('\n');
  111. return 0;
  112. }
  113.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty