[英]level order traversal in a binary tree using queue
the following code crashes at runtime but works perfectly fine if struct node* a[10] is declared globally .Where does the problem lie.Any insight would be appreciated. 下面的代码在运行时崩溃,但是如果全局声明struct node * a [10]则可以正常工作。问题出在哪里。 Thank you!
谢谢!
#include<bits/stdc++.h>
using namespace std;
int rear=-1;
int front=-1;
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int d){
struct node* node1=new node;
node1->data=d;
node1->left=NULL;
node1->right=NULL;
return(node1);
}
void enqueue(struct node* a[],struct node* tempnode){
rear++;
a[rear]=tempnode;
}
struct node* dequeue(struct node* a[]){
front++;
return a[front];
}
void bfs(struct node* root,struct node* a[]){
struct node *tempnode=root;
while(tempnode){
cout<<tempnode->data;
if(tempnode->left)
enqueue(a,tempnode->left);
if(tempnode->right)
enqueue(a,tempnode->right);
tempnode=dequeue(a);
}
}
main() {
struct node* a[10];
struct node* root=newnode(1);
root->left=newnode(2);
root->right=newnode(3);
root->left->left=newnode(-1);
root->left->right=newnode(0);
bfs(root,a);
}
http://www.geeksforgeeks.org/level-order-tree-traversal/ http://www.geeksforgeeks.org/level-order-tree-traversal/
Initialize the array "a" - 初始化数组“ a”-
int main() {
struct node* a[10] = {NULL};
The problem is not occurring when struct node* a[10] is declared globally because global variables are initialized automatically. 全局声明结构节点* a [10]时不会发生此问题,因为全局变量是自动初始化的。
You forget to initialize a
: 你忘了初始化
a
:
struct node* a[10]{};
so your dequeue
will indeed return nullptr
once your queue is empty. 因此,一旦队列为空,
dequeue
确实会返回nullptr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.