Vertical Traversal of a Binary Tree using BFS (original) (raw)
Last Updated : 04 Feb, 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:
**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.
**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 #include #include #include 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> 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: