级别顺序遍历分段错误

Level Order traversal Segmentation fault

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

我正在尝试一个二进制树的简单级别顺序遍历,但它说我有一个segfault。我正在为我正在使用的函数编写代码。

#include<queue>
/*
 struct node
{
int data;
node* left;
node* right;
}*/
void LevelOrder(node * root)
{
queue<node*> q;
q.push(root);

while(!q.empty())
{
    node* t;
    t=q.front();
    cout<<t->data;
    q.push(t->left);
    q.push(t->right);
    q.pop();
 }
 }

您需要检查leftright是否为空。

if (t->left) {
    q.push(t->left);
}
if (t->right) {
    q.push(t->right);
}

如果root可以为空,您还需要检查它。