-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同時對不對?
謝謝
我感謝代碼的空白,但在這裏它只是分心的內容。代碼縮進也有助於可讀性。 – iRove
似乎這兩個打印都是在'temp == NULL'條件下處理的。 – Arun
@iove同意。道歉 – Anant