Level Order Traversal or Breadth First Traversal of a Tree With Examples [Latest]

Dec 18, 2021

In this tutorial, we’ll be discussing what’s Level Order Traversal. Also, we’ll be printing each level of the tree. We’ll use the two major approaches – Recursive and Iterative and see what’s the difference in time complexities between them.

Level Order Traversal

Level Order traversal is also known as Breadth-First Traversal since it traverses all the nodes at each level before going to the next level (depth).

Following illustration shows levels of a Binary Tree:

The last level of the tree is always equal to the height of the tree.

The last level of the tree should contain at least one Node.

Following is the class that defines the Binary Tree Data Structure:

Let’s write the Java Program for iterative and recursive approaches for breadth-first traversal.

Following Java program uses the recursive approach to print each level of the tree:

Following is the output that gets printed:

Level Order Complexity for Recursive ApproachTime Complexity – O(n^2)
Space Complextiy – O(1)

Let’s optimize the above program by using the Iterative approach instead.

This prints the following:

In the above code, each Node is enqueued and dequeued once.

Level Order Complexity for Iterative ApproachTime Complexity – O(n)
Space Complextiy – O(n)

The Queue size is equal to the number of the nodes.

So in the above approach, we’ve traded with some space for optimizing the approach.

That brings an end to this tutorial.

You can checkout complete code and more DS & Algorithm examples from our GitHub Repository.