title: Inserting element in binary tree
body: <p>The code is for inserting an element in a binary tree using level order traversal. I'll first tell u how it works. It first goes through the nodes in each level and if there is any node which doesn't have both children it inserts the node as a child to that node and it use's queue for storing and retrieving the nodes addresses. My problem is that every time I call the create function the root value which is passed is always null even after inserting a node the root value is not changed and it's still a null. I am unable to figure out what's wrong in this. Can anyone help me out?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct node
  {
     int data;
     struct node *left,*right;
  }*root;
  
  struct queue
  {
     int capacity,rear,front;
     struct node **qu;
  };
  
  
  void enqueue(struct queue *q,struct node *n)
  {
     q-&gt;front=(++(q-&gt;front))%q-&gt;capacity;
     (q-&gt;qu)[q-&gt;front]=n;
     if(q-&gt;rear==-1)
     q-&gt;rear++;
  }
  
  struct node* dequeue(struct queue *q)
  {
     struct node *temp;
     temp=q-&gt;qu[q-&gt;rear];
     if(q-&gt;front==q-&gt;rear)
     q-&gt;front=q-&gt;rear=-1;
     else
     q-&gt;rear=(++(q-&gt;rear))%q-&gt;capacity;
  }
  
  int isempty(struct queue *q)
  {
     return(q-&gt;rear==-1);
  }
  
  struct queue* create(unsigned int capacity)
  {
     struct queue *p;
     p=(struct queue*)malloc(sizeof(struct queue));
     p-&gt;capacity=capacity;
     p-&gt;front=p-&gt;rear=-1;
     p-&gt;qu=(struct node**)malloc(sizeof(struct node)*capacity);
     return p;
  }
  
  
   void insert(struct node *root)
   {
      int n;
      struct node *p,*q;
      struct queue *tmp;
      p=(struct node*)malloc(sizeof(struct node));
      p-&gt;left=p-&gt;right=NULL;
      scanf("%d",&amp;n);
      p-&gt;data=n;
      if(root==NULL)
      {
        root=p;
        return;
      }
      tmp=create(20);
      enqueue(tmp,root);
      while(isempty(tmp))
      {
        q=dequeue(tmp);
        printf("%d %d\n",p,root);
        if((!q-&gt;right)||(!q-&gt;left))
        {
            if(!q-&gt;right)
            q-&gt;right=p;
            else
            q-&gt;left=p;
            return;
        }
        else
        {
           enqueue(tmp,q-&gt;left);
           enqueue(tmp,q-&gt;right);
        }
      }
   }
  
   void traverse(struct node *root)
   {
     if(!root)
     return;
     traverse(root-&gt;left);
     printf("%d ",root-&gt;data);
     traverse(root-&gt;right);
   }
  
  void main()
  {
     int i,n;
     while(1)
     {
         printf("1.insert\n2.exit\n");
         scanf("%d",&amp;n);
         switch(n)
         {
            case 2:goto end;
            case 1:insert(root);
         }
      }
      end:
      traverse(root);
   }
  </code></pre>
  
  <p>Thanks.</p>