通过队列访问节点时出现运行时错误

时间:2016-08-03 09:29:47

标签: binary-tree

我正在尝试连接处于同一级别的二叉树的节点 我正在使用队列来做到这一点。最初我已将根推入队列。但是在第12行执行第一个if语句时 if(q.front() - > left!= NULL)然后我收到运行时错误。 请帮忙

节点结构:

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

连接节点的功能

node* connect(node* root)
{
    if(root=NULL)
        return display(root);
    queue<node*> q;
    int count=0;
    q.push(root);
    count++;
    while(!q.empty())
    {
        cout << "inside while loop\n";
        int i=1,temp=0;
        while(i<=count)
        {
            cout << "inside inner while\n";
            if(q.front()->left!=NULL)
            {
                cout << "inside if 1\n";
                q.push(q.front()->left);
                temp++;
            }
            if(q.front()->right!=NULL)
            {
                cout << "inside if 2\n";
                q.push(q.front()->right);
                temp++;
            }
            node* v=q.front();
            q.pop();
            if(i==count)
                v->nextRight=NULL;
            else
                v->nextRight=q.front();
        }
        count=temp;
    }
    return display(root);
}  

1 个答案:

答案 0 :(得分:0)

您需要在代码中进行大量更改。

错误1:

while(i<=count)

永远不会成真。

错误2:

v->nextRight=q.front();

将nextRight设置为指向Left child。

错误3:

i永远不会改变,那么为什么要声明一个变量并造成混淆。

相关问题