2016-09-28 74 views
-2

我正在尝试编写一个程序来通过树中广度优先方式。C中的意外输出(遍历树)

这里是我的代码:

#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同时对不对?

谢谢

+3

我感谢代码的空白,但在这里它只是分心的内容。代码缩进也有助于可读性。 – iRove

+0

似乎这两个打印都是在'temp == NULL'条件下处理的。 – Arun

+0

@iove同意。道歉 – Anant

回答

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

缩进。应该做更多的。谢谢一堆! – Anant