The problem with your algorithm is that nodes, all on the same level, mistakenly increase the number of levels.
Explanation:
Set root level to 0
When you add nodes at any level, set their level to 1 higher than the level of their parent.
As soon as you get any node that has a level number equal to the required level number, it simply breaks out of the BFS and discard all the nodes in the queue behind the current node that have the same level number.
See the comment for more details.
Here is one solution:
void Tree::printSameLevel(int requiredLevel) { queue BFSQ; TreeNode * temp; BFSQ.push(getHead()); while(!BFSQ.empty()) { temp = BFSQ.front(); BFSQ.pop(); //if the level of the current node is equal to the //required level, we can stop processing now and simply //remove from the queue all the elements that follow //and have the same level number. //It follows from properties of BFS that such elements //will occur in a series ( level by level traversal). if(temp->level == requiredLevel) { break; } if(temp->right) { BFSQ.push(temp->right); temp->right->level = temp->level + 1; } if(temp->left) { BFSQ.push(temp->left); temp->left->level = temp->level + 1; } } if(!BFSQ.empty() || requiredLevel==0) { cout << "Printing all the nodes at level " << requiredLevel << " : "; while(temp&&temp->level == requiredLevel) { cout << temp->data << " "; temp = BFSQ.front(); BFSQ.pop(); } } }
Here is an example output:
5 7 3 8 6 4 2 TREE STATS _____________________ Inorder Trace = 2 3 4 5 6 7 8 Height = 2 Internal Nodes = 3 Leaf Nodes = 4 Total Nodes = 7 _____________________ Trees printed above are mirrors! Printing all the nodes at level 0 : 5 Printing all the nodes at level 1 : 7 3
If you're interested, I added a function to the implementation of common roles here . You will find a large number of tree operations for reference (mirror, height, beautiful printing, etc.).
axiom source share