DLU-1031 旋转吧!葱!

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <malloc.h>
  4 #include <string.h>
  5 #include <stdbool.h>
  6 #include <math.h>
  7 #define MAX 1500
  8  
  9 struct TreeNode
 10 {
 11     int val;
 12     struct TreeNode *left;
 13     struct TreeNode *right;
 14 };
 15  
 16 typedef struct seqqueue
 17 {
 18     struct TreeNode* data[MAX];
 19     int front;
 20     int rear;
 21 } seqqueue;
 22  
 23 void enter(seqqueue *q,struct TreeNode* t)
 24 {
 25     q->data[q->rear] = t;
 26     q->rear++;
 27 }
 28  
 29 struct TreeNode* del(seqqueue *q)
 30 {
 31     if(q->front == q->rear)
 32     {
 33         return NULL;
 34     }
 35     else
 36     {
 37         q->front++;
 38         return q->data[q->front-1];
 39     }
 40 }
 41  
 42 void level_tree(struct TreeNode* t)
 43 {
 44     seqqueue q;
 45     struct TreeNode* temp;
 46     q.front = q.rear = 0;
 47     if(!t)
 48     {
 49         return ;
 50     }
 51     enter(&q,t);
 52     while(q.front != q.rear)
 53     {
 54         t=del(&q);
 55         printf("%d ",t->val);
 56         if(t->left)
 57         {
 58             enter(&q,t->left);
 59         }
 60         if(t->right)
 61         {
 62             enter(&q,t->right);
 63         }
 64     }
 65 }
 66  
 67 void exchange(struct TreeNode *root)
 68 {
 69     struct TreeNode *node = root;
 70     if(node != NULL)
 71     {
 72         struct TreeNode *temp = node -> left;
 73         node -> left = node -> right;
 74         node -> right = temp;
 75     }
 76 }
 77  
 78 struct TreeNode* invertTree(struct TreeNode* root)
 79 {
 80     struct TreeNode *node = root;
 81     if(root == NULL)
 82     {
 83         return root;
 84     }
 85     invertTree(node->left);
 86     invertTree(node->right);
 87     exchange(node);
 88     return root;
 89 }
 90  
 91 int main()
 92 {
 93     int node_num;
 94     while(~scanf("%d",&node_num))
 95     {
 96         struct TreeNode *node[node_num];
 97         int i;
 98         for(i = 0; i < node_num; i ++)
 99         {
100             node[i] = malloc(sizeof(struct TreeNode));
101             scanf("%d",&node[i]->val);
102             if(node[i]->val==-1)
103             {
104                 node[i] = NULL;
105                 continue;
106             }
107             node[i] -> left = NULL;
108             node[i] -> right = NULL;
109         }
110         for(i = node_num-1; i > 0; i --)
111         {
112             if(i & 0x1)
113             {
114                 node[i/2]->left = node[i];
115             }
116             else
117             {
118                 node[i/2-1]->right = node[i];
119             }
120         }
121         struct TreeNode *root = invertTree(node[0]);
122         level_tree(root);
123         printf("\n");
124     }
125     return 0;
126 }

 

posted @ 2018-08-23 18:01  Asurudo  阅读(152)  评论(0编辑  收藏  举报