请在此程序中建议关卡顺序树遍历的错误

Please suggest error in this program for level order tree traversal

本文关键字:顺序 遍历 错误 程序      更新时间:2023-10-16

请在此程序中建议关卡顺序树遍历的错误我得到一个无限循环,全部打印 1

算法:

对于每个节点,首先访问该节点,然后将其子节点放入 FIFO 队列中。

打印级别顺序(树(

1.Create an empty queue q
2.temp_node = root /*start from root*/
3.Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node

#include<iostream>

这是树的节点

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

这是队列的节点,用于保存树的节点

struct qnode
{
struct node *node;
struct qnode *next;
};
struct frontandrear
{
struct qnode *front;
struct qnode *rear;
};

struct node* newNode( int data )
{
struct node *new_node = (struct node*)malloc( sizeof( struct node ) );
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}

void enQueue( struct frontandrear *fr, struct node* node )
{
struct qnode* new_node = (struct qnode*)malloc( sizeof( struct qnode ) );
new_node->node = node;
if (fr->rear == NULL)
    {
    new_node->next = NULL;
    fr->rear = new_node;
    fr->front = new_node;
    }
else
    {
    new_node->next = fr->rear;
    fr->rear = new_node;
    }
}
struct node* deQueue( struct frontandrear *fr )
{
if (fr->front == NULL)
    {
    return NULL;
    }
struct node* num = fr->front->node;
fr->front = fr->front->next;
if (fr->front == NULL)
    {
    fr->front = fr->rear = NULL;
    }
return num;
}
void printLevelOrder( struct node* root )
{
struct frontandrear *frontandrear = (struct frontandrear*)malloc( sizeof(     struct frontandrear ) );
frontandrear->front = frontandrear->rear = NULL;
struct node *temp = root;
while (temp != NULL)
    {
    printf( "%dt", root->data );
    if (temp->left)
        enQueue( frontandrear, root->left );
    if (temp->right)
        enQueue( frontandrear, root->right );
    temp = deQueue( frontandrear );
    }
}

int main( )
{
struct node *root = newNode( 1 );
root->left = newNode( 2 );
root->right = newNode( 3 );
root->left->left = newNode( 4 );
root->left->right = newNode( 5 );
printf( "Level Order traversal of binary tree is n" );
printLevelOrder( root );
}

在你的 while 循环中:

while (temp != NULL)
    {
    printf( "%dt", root->data );
    if (temp->left)
        enQueue( frontandrear, root->left );
    if (temp->right)
        enQueue( frontandrear, root->right );
    temp = deQueue( frontandrear );
    }
}

enQueue的第二个参数中,您正在使用我认为您打算使用temproot