Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Vertical Zig-Zag traversal of a Tree
Next article icon

Vertical Traversal of a Binary Tree using BFS

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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.

C++
//Driver Code Starts{ // C++ code of Vertical Traversal of  // a Binary Tree using BFS and Hash Map  #include <iostream> #include <vector> #include <queue> #include <unordered_map> using namespace std;  class Node { public:     int data;     Node *left, *right;     Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } }; //Driver Code Ends }   vector<vector<int>> verticalOrder(Node *root) {        unordered_map<int, vector<int>> mp;       int hd = 0;        // Create a queue for level order traversal       queue<pair<Node*, int>> q;       q.push({ root, 0 });        // mn and mx contain the minimum and maximum       // horizontal distance from root       int mn = 0, mx = 0;       while (!q.empty()) {          // Pop from queue front         pair<Node*, int> curr = q.front();         q.pop();          Node* node = curr.first; 		hd = curr.second;          // Insert this node's data in the         // array of the 'hd' level in map         mp[hd].push_back(node->data);          if (node->left)               q.push({ node->left, hd - 1 });         if (node->right)               q.push({ node->right, hd + 1 });          // Update mn and mx         mn = min(mn, hd);         mx = max(mx, hd);       }          vector<vector<int>> res;          // Traverse the map from minimum to        // maximum horizontal distance (hd)       for (int i = mn; i <= mx; i++) {           res.push_back(mp[i]);       }       return res; }       //Driver Code Starts{ int main() {        // Constructing the binary tree:     //        1     //       / \     //      2   3     //     / \ / \     //    4  5 6  7     //          \  \     //           8  9     Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);     root->left->right = new Node(5);     root->right->left = new Node(6);     root->right->right = new Node(7);     root->right->left->right = new Node(8);     root->right->right->right = new Node(9);        vector<vector<int>> res = verticalOrder(root);          for(vector<int> temp: res) {         cout << "[ ";         for (int val: temp)              cout << val << " ";         cout << "] ";     }          return 0; }  //Driver Code Ends } 
Java
//Driver Code Starts{ // Java code of Vertical Traversal of  // a Binary Tree using BFS and HashMap  import java.util.*;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } } //Driver Code Ends }   // Custom Pair class class Pair<U, V> {     public final U first;     public final V second;      Pair(U first, V second) {         this.first = first;         this.second = second;     } }  class GfG {          // Function to perform vertical order traversal of a binary tree     static ArrayList<ArrayList<Integer>> verticalOrder(Node root) {                  HashMap<Integer, ArrayList<Integer>> mp = new HashMap<>();         int hd = 0;          // Create a queue for level order traversal         Queue<Pair<Node, Integer>> q = new LinkedList<>();         q.add(new Pair<>(root, 0));          // mn and mx contain the minimum and maximum         // horizontal distance from root         int mn = 0, mx = 0;         while (!q.isEmpty()) {              // Pop from queue front             Pair<Node, Integer> curr = q.poll();             Node node = curr.first;             hd = curr.second;              // Insert this node's data in the             // array of the 'hd' level in map             mp.computeIfAbsent(hd, k -> new ArrayList<>()).add(node.data);              if (node.left != null)                 q.add(new Pair<>(node.left, hd - 1));             if (node.right != null)                 q.add(new Pair<>(node.right, hd + 1));              // Update mn and mx             mn = Math.min(mn, hd);             mx = Math.max(mx, hd);         }          ArrayList<ArrayList<Integer>> res = new ArrayList<>();                  // Traverse the map from minimum to          // maximum horizontal distance (hd)         for (int i = mn; i <= mx; i++) {             res.add(mp.get(i));         }         return res;     }   //Driver Code Starts{     public static void main(String[] args) {                  // Constructing the binary tree:         //        1         //       / \         //      2   3         //     / \ / \         //    4  5 6  7         //          \  \         //           8  9         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);         root.right.left.right = new Node(8);         root.right.right.right = new Node(9);          ArrayList<ArrayList<Integer>> res = verticalOrder(root);                  for (ArrayList<Integer> temp : res) {             System.out.print("[ ");             for (int val : temp)                  System.out.print(val + " ");             System.out.print("] ");         }     } }  //Driver Code Ends } 
Python
#Driver Code Starts{ # Python code of Vertical Traversal of  # a Binary Tree using BFS and Hash Map  from collections import defaultdict, deque  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None #Driver Code Ends }   # Function to perform vertical order traversal of a binary tree def verticalOrder(root):          mp = defaultdict(list)     hd = 0      # Create a queue for level order traversal     q = deque([(root, 0)])      # mn and mx contain the minimum and maximum     # horizontal distance from root     mn, mx = 0, 0     while q:          # Pop from queue front         node, hd = q.popleft()          # Insert this node's data in the         # array of the 'hd' level in map         mp[hd].append(node.data)          if node.left:             q.append((node.left, hd - 1))         if node.right:             q.append((node.right, hd + 1))          # Update mn and mx         mn = min(mn, hd)         mx = max(mx, hd)          res = []          # Traverse the map from minimum to      # maximum horizontal distance (hd)     for i in range(mn, mx + 1):         res.append(mp[i])          return res   #Driver Code Starts{ if __name__ == "__main__":      # Constructing the binary tree:     #        1     #       / \     #      2   3     #     / \ / \     #    4  5 6  7     #          \  \     #           8  9     root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)     root.left.right = Node(5)     root.right.left = Node(6)     root.right.right = Node(7)     root.right.left.right = Node(8)     root.right.right.right = Node(9)      res = verticalOrder(root)          for temp in res:         print("[", " ".join(map(str, temp)), "]", end=" ")  #Driver Code Ends } 
C#
//Driver Code Starts{ // C# code of Vertical Traversal of  // a Binary Tree using BFS and HashMap  using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG { //Driver Code Ends }           static List<int[]> verticalOrder(Node root) {                  Dictionary<int, List<int>> mp = new Dictionary<int, List<int>>();         int hd = 0;          // Create a queue for level order traversal         Queue<Tuple<Node, int>> q = new Queue<Tuple<Node, int>>();         q.Enqueue(new Tuple<Node, int>(root, 0));          // mn and mx contain the minimum and maximum         // horizontal distance from root         int mn = 0, mx = 0;         while (q.Count > 0) {              // Pop from queue front             var curr = q.Dequeue();             Node node = curr.Item1;             hd = curr.Item2;              // Insert this node's data in the             // array of the 'hd' level in map             if (!mp.ContainsKey(hd))                  mp[hd] = new List<int>();              mp[hd].Add(node.data);              if (node.left != null)                 q.Enqueue(new Tuple<Node, int>(node.left, hd - 1));             if (node.right != null)                 q.Enqueue(new Tuple<Node, int>(node.right, hd + 1));              // Update mn and mx             mn = Math.Min(mn, hd);             mx = Math.Max(mx, hd);         }          List<int[]> res = new List<int[]>();          // Traverse the map from minimum to          // maximum horizontal distance (hd)         for (int i = mn; i <= mx; i++) {             res.Add(mp[i].ToArray());         }                  return res;     }   //Driver Code Starts{     public static void Main() {                  // Constructing the binary tree:         Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);         root.right.left.right = new Node(8);         root.right.right.right = new Node(9);          List<int[]> res = verticalOrder(root);                  foreach (int[] temp in res) {             Console.Write("[ ");             foreach (int val in temp)                  Console.Write(val + " ");             Console.Write("] ");         }     } }  //Driver Code Ends } 
JavaScript
//Driver Code Starts{ // JavaScript code of Vertical Traversal of  // a Binary Tree using BFS and Hash Map  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } } //Driver Code Ends }   // Function to perform vertical order traversal of a binary tree function verticalOrder(root) {      let mp = new Map();     let hd = 0;      // Create a queue for level order traversal     let q = [[root, 0]];      // mn and mx contain the minimum and maximum     // horizontal distance from root     let mn = 0, mx = 0;      while (q.length > 0) {          // Pop from queue front         let [node, hd] = q.shift();          // Insert this node's data in the         // array of the 'hd' level in map         if (!mp.has(hd)) {             mp.set(hd, []);         }         mp.get(hd).push(node.data);          if (node.left)             q.push([node.left, hd - 1]);         if (node.right)             q.push([node.right, hd + 1]);          // Update mn and mx         mn = Math.min(mn, hd);         mx = Math.max(mx, hd);     }      let res = [];      // Traverse the map from minimum to      // maximum horizontal distance (hd)     for (let i = mn; i <= mx; i++) {         res.push(mp.get(i));     }     return res; }   //Driver Code Starts{ // Driver Code // Constructing the binary tree: //        1 //       / \ //      2   3 //     / \ / \ //    4  5 6  7 //          \  \ //           8  9 let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); root.right.right.right = new Node(9);  let res = verticalOrder(root);  let output = ""; res.forEach(temp => {     output += "[ ";     temp.forEach(val => output += val + " ");     output += "] "; }); console.log(output);  //Driver Code Ends } 

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

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

Related articles:

  • Vertical Traversal Brute Force
  • Vertical Traversal Depth First Based




Next Article
Vertical Zig-Zag traversal of a Tree

S

Sahil Chhabra (akku)
Improve
Article Tags :
  • DSA
  • Hash
  • Tree
  • Amazon
  • BrowserStack
  • Dell
  • Flipkart
  • Grofers
  • MakeMyTrip
  • tree-level-order
Practice Tags :
  • Amazon
  • BrowserStack
  • Dell
  • Flipkart
  • Grofers
  • MakeMyTrip
  • Hash
  • Tree

Similar Reads

  • Vertical Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[4], [2], [1, 5, 6], [3,
    10 min read
  • Vertical Traversal using Brute Force
    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: Output: [[
    11 min read
  • Triple Order Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its Triple Order Traversal. Triple Order Traversal is a tree traversal technique in which every node is traversed thrice in the following order: Visit the root nodeTraverse the left subtreeVisit the root nodeTraverse the right subtreeVisit the root node.Examp
    7 min read
  • Vertical Zig-Zag traversal of a Tree
    Given a Binary Tree, the task is to print the elements in the Vertical Zig-Zag traversal order. Vertical Zig-Zag traversal of a tree is defined as: Print the elements of the first level in the order from right to left, if there are no elements left then skip to the next level.Print the elements of t
    15 min read
  • Left View of a Binary Tree Using Stack
    Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level. Examples: Example 1 : The Green colored nodes represents the left view in the below Binary tree. Example 2: The Green colored nodes represents the le
    8 min read
  • Vertical width of Binary tree | Set 2
    Given a binary tree, find the vertical width of the binary tree. The width of a binary tree is the number of vertical paths. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 5 Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output : 6 Prerequisite: Print Binary Tree in Vertical order In this image, th
    5 min read
  • Vertical width of Binary tree | Set 1
    Given a Binary tree, the task is to find the vertical width of the Binary tree. The width of a binary tree is the number of vertical paths in the Binary tree. Examples: Input: Output: 6Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree. Input : 7
    14 min read
  • Vertical Sum in a given Binary Tree
    Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Input: Output: 4 2 12 11 7 9Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level. Table of Content Using map - O
    15 min read
  • DFS traversal of a Tree
    Depth-First Search (DFS) is a method used to explore all the nodes in a tree by going as deep as possible along each branch before moving to the next one. It starts at the root node and visits every node in the tree. Depth-First Search (DFS) can be classified into three main types based on the order
    13 min read
  • Sum of all vertical levels of a Binary Tree
    Given a binary tree consisting of either 1 or 0 as its node values, the task is to find the sum of all vertical levels of the Binary Tree, considering each value to be a binary representation. Examples: Input: 1 / \ 1 0 / \ / \ 1 0 1 0Output: 7Explanation: Taking vertical levels from left to right:F
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences