Anant Anant - 2 months ago 22
C Question

Unexpected output in C (Traversal of Trees)

I'm trying to code a program to go through a Tree in Breadth First Manner.

Here is my code :

#include<stdio.h>
#include<stdlib.h>

struct TreeNode
{
struct TreeNode *right;
struct TreeNode *left ;
int data;
};

struct TreeNode* newTreeNode(int data)
{
struct TreeNode* temp = (struct TreeNode*)malloc(sizeof(struct TreeNode));

temp->data = data;
temp->right=NULL;
temp->left=NULL;
return temp;
}

struct QueueNode
{
struct QueueNode *next;
struct TreeNode *tree_element;
} *head,*tail;

void initQueue()
{
head=NULL;
tail=NULL;
}

void enQueue(struct TreeNode *ptr)
{
struct QueueNode *temp = (struct QueueNode *)malloc(sizeof(struct QueueNode));

if(head==NULL)
{
temp->next=NULL;
temp->tree_element = ptr;
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
temp->tree_element = ptr;
temp->next = NULL;
}
}

struct QueueNode* deQueue()
{
struct QueueNode *temp = NULL;

if(head==NULL) /*Empty Queue so return NULL*/
{
printf("Empty queue\n");
return NULL;
}
{
temp = head;
head = head->next;
return temp;
}
}

int main()
{
struct QueueNode *temp = NULL;

/* Initializing tree structure */
struct TreeNode *root = newTreeNode(1);

initQueue();
enQueue(root); /* Root in the queue */

temp = head;

while(temp!=NULL)
{
//printf("entering loop");
temp = deQueue();
if(temp==NULL)
{
printf("Dequeue and Temp is NULL\n");
//break;
}
else if(temp!=NULL)
{
if(temp->tree_element->left!=NULL)
{
enQueue(temp->tree_element->left) ;
}
if(temp->tree_element->right!=NULL)
{
enQueue(temp->tree_element->right);}
}
/*
if(temp->tree_element!=NULL)*/
if(temp==NULL)
printf("Whatever\n");
}

return 0;
}


The output is :

Empty queue

Dequeue and Temp is NULL

Whatever


My question is :

How do

Dequeue and Temp is NULL


and

Whatever


get printed at the same time. temp can't be NULL and !NULL at the same time right ?

Thank You

Answer

To answer your question, you have your two printfs under same condition:

  if(temp==NULL) //<---- temp == NULL condition
            {
                printf("Dequeue and Temp is NULL\n");
                //break;
            }
  else if(temp->tree_element->right!=NULL)
            {
                enQueue(temp->tree_element->right);} //<-- If you play little hide-n-seek with your beautifully aligned code you may find this hidden curly brace

        if(temp==NULL) //<---- Same condition
            printf("Whatever\n");
    }