Given a binary tree, perform vertical traversal on it. In a vertical traversal, nodes of a binary tree are processed in vertical order from left to right. Assume that the left and right child makes a 45–degree angle with the parent.

For example, a vertical traversal of the following binary tree is

2, 7
1, 5
3, 8
6

 
Vertical Traversal

Practice this problem

We can easily solve this problem with the help of hashing. This post provides an overview of some available alternatives to accomplish this using hashing.

1. Using Preorder Traversal

The idea is to create an empty map where each key represents the relative horizontal distance of a node from the root node, and the value in the map maintains all nodes present at the same horizontal distance. Then perform a preorder traversal of the tree, and update the map. For each node, recur for its left subtree by decreasing horizontal distance by 1 and recur for the right subtree by increasing horizontal distance by 1. For the above binary tree, the final values in the map will be:

(horizontal distance —> Nodes)
 
-1 —> [2, 7]
0 —> [1, 5]
1 —> [3, 8]
2 —> [6]

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

2 7
1 5 9
3 8
10 6

Java


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[10, 6]

Python


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[10, 6]

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the binary tree.

2. Using Level Order Traversal

Since the above solution uses preorder traversal to traverse the tree, the nodes might not get processed in the same order as they appear in the binary tree from top to bottom. For instance, node 10 is printed before node 6 in the above solution.

We can perform a level order traversal to ensure that nodes are processed in the same order as they appear in the binary tree. The idea remains the same as the previous approach – create an empty map whose each key represents the relative horizontal distance of a node from the root node, and the value in the map maintains all nodes present at the same horizontal distance. The only difference is that the binary tree is traversed using level order traversal instead of the preorder traversal.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

2 7
1 5 9
3 8
6 10

Java


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[6, 10]

Python


Download  Run Code

Output:

[2, 7]
[1, 5, 9]
[3, 8]
[6, 10]

The time complexity of the above solution is O(n.log(n)) and requires O(n) extra space, where n is the size of the binary tree.

 
Linear Time Solution:

Print nodes of a binary tree in vertical order

 
Exercise: Reduce time complexity to linear using std::unordered_map/HashMap.