我正在尝试连接处于同一级别的二进制树的节点我用一个队列来做这件事。最初我已经把根推到了队列中。但在第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 loopn";
int i=1,temp=0;
while(i<=count)
{
cout << "inside inner whilen";
if(q.front()->left!=NULL)
{
cout << "inside if 1n";
q.push(q.front()->left);
temp++;
}
if(q.front()->right!=NULL)
{
cout << "inside if 2n";
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:
while(i<=count)
永远不会是真的。
错误2:
v->nextRight=q.front();
将设置nextRight指向Left子对象。
错误3:
i
永远不会改变,那么为什么要声明一个变量并造成混乱呢。