title: tree data structure (level_order)
body: <p>I'm learning tree data structure about <code>preorder</code>, <code>postorder</code>, <code>inorder</code> and <code>level_order</code>. These code are written by C. When i assign the <code>temp -&gt; item</code> to element item in dequeue method, make the error. But i think <code>struct</code> pointer can save another <code>struct</code> pointer! how can i solve it   </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;malloc.h&gt;
  
  typedef struct QueueNode {
      int item;
      struct QueueNode *link; 
  } QueueNode;
  typedef struct {
      QueueNode *front, *rear;
  } QueueType;
  
  typedef struct TreeNode {
      int data;
      struct TreeNode *left, *right;
  } TreeNode;
  
  typedef TreeNode * element;
  
  
  void error(char *message)
  {
  fprintf(stderr,"%s\n",message);
  exit(1);
  }
  
  
  void init(QueueType *q)
  {
      q-&gt;front = q-&gt;rear = 0;
  }
  
  int is_empty(QueueType *q)
  {
      return (q-&gt;front==NULL);
  }
  
  int is_full(QueueType *q)
  {
      return 0;
  }
  
  void enqueue(QueueType *q, element item)
  { 
      QueueNode *temp=(QueueNode *)malloc(sizeof(QueueNode)); 
      if(temp == NULL )
          error("error");
      else {
          temp-&gt;item = item;
          temp-&gt;link = NULL;
          if( is_empty(q) ){
              q-&gt;front = temp;
              q-&gt;rear = temp;     
          }
          else {
              q-&gt;rear-&gt;link = temp;
              q-&gt;rear = temp; 
          }   
      }
  }
  
  element dequeue(QueueType *q) 
  { 
      QueueNode *temp = q -&gt; front;
      element item; 
      if( is_empty(q) )
          error("error");
      else {
          item = temp-&gt;item;
          q-&gt;front = q-&gt;front-&gt;link;
          if( q-&gt;front == NULL )
          q-&gt;rear = NULL;
          free(temp);
          return item;
      }
  } 
  
  
  void level_order(TreeNode *ptr)
  {
      QueueType q;
  
      init(&amp;q);
      if( !ptr ) return;
      enqueue(&amp;q, ptr);
      while(is_empty(&amp;q)) {
          ptr = dequeue(&amp;q);
          printf(" %d ", ptr-&gt;data);
          if( ptr-&gt;left )
              enqueue(&amp;q, ptr-&gt;left);
          if( ptr-&gt;right )
              enqueue(&amp;q, ptr-&gt;right);
      }
  }
  
  TreeNode n1={1,  NULL, NULL};
  TreeNode n2={2,  &amp;n1,  NULL};
  TreeNode n3={4, NULL,  NULL};
  TreeNode n4={8, NULL, NULL};
  TreeNode n5={10, NULL, NULL};
  TreeNode n6={6, NULL, NULL};
  TreeNode n7={9, &amp;n4,  &amp;n5};
  TreeNode n8={7, &amp;n6, &amp;n7};
  TreeNode n9={3, &amp;n2,  &amp;n3};
  TreeNode n10={5, &amp;n9,  &amp;n8};
  TreeNode *root= &amp;n10;
  
  
  
  void main()
  {
      level_order(root);
  
  }
  </code></pre>