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?
A Level Order Traversal is a traversal which always traverses based on the level of the tree. So, this traversal first traverses the nodes corresponding to Level 0, and then Level 1, and so on, from the root node. In the example Binary Tree above, the level order traversal will be: (Root) 10 -> 20 -> 30 -> 40 -> 50.
Introduction to level order traversal This is called level order traversal or breadth-first search traversal. In the short form, we also call it BFS traversal. A binary tree is organized in different levels where root node is at the topmost level (0th level).
Level Order Traversal or Breadth-First SearchBreadth-First Search (BFS) also known as Level Order Traversal is one of the techniques to traverse the tree. This technique traverses the tree in a level-by-level fashion. We will use a Queue data structure to achieve this. Here are the steps of our algorithm.
void traverse(Node* root)
{
queue<Node*> q;
if (root) {
q.push(root);
}
while (!q.empty())
{
const Node * const temp_node = q.front();
q.pop();
cout<<temp_node->value<<"\n";
if (temp_node->left) {
q.push(temp_node->left);
}
if (temp_node->right) {
q.push(temp_node->right);
}
}
}
There, no more special case. And the indentation is cleaned up so it can be understood more easily.
Alternatively:
void traverse(Node* root)
{
queue<Node*> q;
if (!root) {
return;
}
for (q.push(root); !q.empty(); q.pop()) {
const Node * const temp_node = q.front();
cout<<temp_node->value<<"\n";
if (temp_node->left) {
q.push(temp_node->left);
}
if (temp_node->right) {
q.push(temp_node->right);
}
}
}
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.
You can try this way:
struct Node
{
char data;
Node* left;
Node* right;
};
void LevelOrder(Node* root)
{
if(root == NULL) return;
queue<Node*> Q;
Q.push(root);
while(!Q.empty())
{
Node* current = Q.front();
cout<< current->data << " ";
if(current->left != NULL) Q.push(current->left);
if(current->right != NULL) Q.push(current->right);
Q.pop();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With