Given a binary tree, print the top view of it. Assume the left and right child of a node makes a 45–degree angle with the parent.

For example, the top view of the following tree is 2, 1, 3, 6:

 
Top View of Binary Tree

Practice this problem

We can easily solve this problem with the help of hashing. The idea is to create an empty map where each key represents the relative horizontal distance of the node from the root node, and the value in the map maintains a pair containing the node’s value and its level number. Then perform preorder traversal on the tree. Suppose the current node’s level is less than the maximum level seen so far for the same horizontal distance as the current node or current horizontal distance is seen for the first time. In that case, update the value and the level for the current horizontal distance in the map. For each node, recur for its left subtree by decreasing horizontal distance and increasing level by one, and recur for right subtree by increasing both level and horizontal distance by one.

 
The following figure shows the horizontal distance and level of each node in the above binary tree:

Horizontal distance vs Level – Binary Tree

The final values in the map will be:

horizontal distance —> (node’s value, node’s level)
-1 —> (2, 2)
0 —> (1, 1)
1 —> (3, 2)
2 —> (6, 3)

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

C++


Download  Run Code

Output:

2 1 3 6

Java


Download  Run Code

Output:

2 1 3 6

Python


Download  Run Code

Output:

2 1 3 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.

 
Exercise:

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

2. Modify the solution to print the bottom view of a binary tree.