请在此程序中建议关卡顺序树遍历的错误
Please suggest error in this program for level order tree traversal
请在此程序中建议关卡顺序树遍历的错误我得到一个无限循环,全部打印 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
的第二个参数中,您正在使用我认为您打算使用temp
的root
。
相关文章:
- 在循环中按顺序遍历成员变量
- 二叉树级别顺序遍历在leetcode中
- 使用二叉树的关卡顺序概念的垂直顺序遍历
- 按顺序遍历 AVL 树,将值保存在数组中
- 树木中的BFS(级别顺序遍历)
- 按特定顺序遍历 NxN 矩阵的上三角形
- 执行策略如何用于C++中的顺序遍历算法
- 二叉树级别顺序遍历 LeetCode
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 使用队列在二进制树中的水平顺序遍历
- 二进制树的水平顺序遍历
- 二叉树顺序遍历在C++
- 二叉树顺序遍历错误:没有用于调用的匹配函数
- 二进制搜索树中按顺序遍历的复杂性(使用迭代器)
- 如何以相反的顺序遍历 boost::d ynamic_bitset
- 关卡顺序遍历:删除子树
- 使用级别顺序遍历将节点插入二叉树
- 二叉树顺序遍历导致堆栈溢出
- 二进制搜索树,按顺序遍历,步骤3逻辑辅助
- 线程内二叉树的插入或顺序遍历有什么问题