Breadth-First Traversal(or Search) of a Tree (Print Nodes Along With Their Level)


As we have already covered about Breadth-First Traversal(or Search) of a Binary Tree or BFS in detail, in this article we will add 1 more feature to the existing method.

We will print the level no along with the node of the tree. So to achieve this we will create a separate class called Pair. It will be a generic class as we have make the data type of the nodes also generic.

It's key will be basically the node and level will be it's value.


Output:


 {key = A, level = 0} ->  {key = B, level = 1} ->  {key = C, level = 1} -> 

 {key = A, level = 0} ->  {key = B, level = 1} ->  {key = C, level = 1} ->  {key = D, level = 2} ->  {key = E, level = 2} -> 

 {key = A, level = 0} ->  {key = B, level = 1} ->  {key = C, level = 1} ->  {key = D, level = 2} ->  {key = E, level = 2} ->  {key = F, level = 3} ->  {key = H, level = 3} -> 

 {key = A, level = 0} ->  {key = B, level = 1} ->  {key = C, level = 1} ->  {key = D, level = 2} ->  {key = E, level = 2} ->  {key = F, level = 3} ->  {key = H, level = 3} ->  {key = G, level = 3} -> 


Post a Comment

0 Comments