VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-a-binary-tree-in-vertical-order-set-3-using-level-order-traversal/

⇱ Vertical Traversal of a Binary Tree using BFS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Vertical Traversal of a Binary Tree using BFS

Last Updated : 23 Jul, 2025

Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level.

Note that if multiple nodes at same level pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.

Examples:  

Input:

👁 Vertical-Taversal-

Output: [[4], [2], [1, 5, 6], [3, 8], [7], [9]]
Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level.

👁 Vertical-Taversal--2

Approach:

The idea is to traverse the tree using BFS and maintain a Hashmap to store nodes at each horizontal distance (HD) from the root. Starting with an HD of 0 at the root, the HD is decremented for left children and incremented for right children. As we traverse, we add each node's value to the hashmap based on its HD. Finally, we collect the nodes from the hashmap in increasing order of HD to produce the vertical order of the tree.


Output
[ 4 ] [ 2 ] [ 1 5 6 ] [ 3 8 ] [ 7 ] [ 9 ] 

Time Complexity: O(n)
Auxiliary Space: O(n)

Related articles:


Comment