Reputation: 119
I was trying to implement BFS on my own and wrote some code for it. I ran the code through debugger and all iterations of the while loop ran fine except the last one. When the last pointer is inside the queue (buffer) , the if condition :
if (l) {
buffer.push(l);
cout << l - > val << endl;
}
becomes true (when it should be false). And it leads to segmentation fault. Why is this happening? Here is the full code...
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node {
int val;
struct node * left;
struct node * right;
};
vector < int > a {
1,
5,
4,
3,
7,
2,
9
};
vector < node > tree(6, {
0,
nullptr,
nullptr
});
void make_tree() {
for (auto i = 0; i < 7; i++) {
tree[i].val = a[i];
}
for (auto j = 0; j < 3; j++) {
tree[j].left = & (tree[2 * (j + 1) - 1]);
tree[j].right = & (tree[2 * (j + 1)]);
}
}
node * temp = & tree[0];
queue < node * > buffer;
void BFS()
{
buffer.push(temp);
node * r = nullptr;
node * l = nullptr;
cout << (buffer.front()) - > val << endl;
while (!buffer.empty())
{
l = (buffer.front() - > left);
if (l) {
buffer.push(l);
cout << l - > val << endl;
}
r = (buffer.front() - > right);
if (r) {
buffer.push(r);
cout << r - > val << endl;
}
buffer.pop();
}
}
int main()
{
make_tree();
BFS();
return 0;
}
Upvotes: 0
Views: 36
Reputation: 60208
You are indexing into tree
from 0 .. 6
, but are only creating 6 node
s. Creating 7 node
s fixes it:
vector < node > tree(7, { 0, nullptr, nullptr });
Upvotes: 1