C中的意外输出(遍历树)

时间:2016-09-28 23:13:26

标签: c pointers data-structures tree

我正在尝试编写一个程序来以广度优先的方式通过树。

这是我的代码:

#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;
}

输出结果为:

Empty queue

Dequeue and Temp is NULL

Whatever

我的问题是:

怎么做

Dequeue and Temp is NULL

Whatever

同时打印。 temp 不能同时为NULL和!NULL吗?

谢谢

1 个答案:

答案 0 :(得分:2)

要回答您的问题,您的两个printfs条件相同:

  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");
    }