void traverse(Node* root)
{
queue<Node*> q;
Node* temp_node= root;
while(temp_node)
{
cout<<temp_node->value<<endl;
if(temp_node->left)
q.push(temp_node->left);
if(temp_node->right)
q.push(temp_node->right);
if(!q.empty())
{
temp_node = q.front();
q.pop();
}
else
temp_node = NULL;
}
}
The above posted code is my level order traversal code. This code works fine for me but One thing I dont like is I am explicitly initializing temp_node = NULL
or I use break. But it does not seem to be a good code to me.
Is there a neat implementation than this or how can I make this code better?
There, no more special case. And the indentation is cleaned up so it can be understood more easily.
Alternatively:
Done up as a
for
loop. Personally, I like the extra variable. The variable name is a nicer shorthand than saying 'q.front()` all the time.My Java solution using Queue data structure and BFS algorithm:
You can try this way:
I think above code snippets allow to print the level order traversal in array format. This code can help to write the solution in form of level order.
Output:
One serious problem with your existing code is it crashes when it is called on an empty tree (
root = NULL
).You need to decide if you want to have
NULL
pointers in the queue or not.If not them you can only enqueue non-
NULL
values.Alternatively if you decide to have
NULL
in the queue you can do:The first method is preferred as a large tree has plenty of
NULL
children (children of leaf nodes) and there is no point in having them enqueued in the queue when we later just don't process them.Try: