I was just trying out some code, not a experienced coder. I implemented(at least think) Level Order traversal and it sorta got done pretty easily. Want to know if its the right approach.
#include<iostream>
#include<queue>
using namespace std;
class node {
public :
node *right;
node *left;
int info;
}*root;
queue<int> inf;
void bfs(node *t)
{
if(t!=NULL)
{
if(t->right!=NULL)
inf.push(t->right->info);
if(t->left!=NULL)
inf.push(t->left->info);
bfs(t->right);
bfs(t->left);
}
}
int main()
{
node *temp = new node();
temp->info = 1;
root = temp;
root->right = new node();
root->right->info = 2;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 3;
root->left->right = root->left->left = NULL;
node *tmp = root;
root=root->right;
root->right = new node();
root->right->info = 4;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 5;
root->left->right = root->left->left = NULL;
root = tmp;
root = root->left;
root->right = new node();
root->right->info = 6;
root->right->right = root->right->left = NULL;
root->left = new node();
root->left->info = 7;
root->left->right = root->left->left = NULL;
root = temp;
node *it;
it = root;
inf.push(root->info);
bfs(root);
for(;inf.size()!=0;)
{
cout<<inf.front()<<" : ";
inf.pop();
}
return 0;
}
This uses a
std::queue<int>to print the nodes in DFS order! Just using a queue somewhere doesn’t make the traversal order BFS. What you want is astd:: queue<node*>where you put the root node. Then you iterate while the queue isn’t empty and in each iteration you take the next node out of the queue and put its children into the queue:Just a few notes:
size()on a container to determine if there are elements: it may e.g. walk through the elements to count them (although none of the standard containers does) andempty()says what you actually want to know ( although it should have been calledis_empty()).nodeobjects.nodeclass a constructor to initialize the pointers for the children and theinfo.