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

For example, the bottom view of the following tree is 7, 5, 8, 6:

 
Bottom 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 more than or equal to the maximum level seen so far for the same horizontal distance as the current node’s 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. The final values in the map will be:

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

Horizontal distance vs Level – Binary Tree

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

C++


Download  Run Code

Output:

7 5 8 6

Java


Download  Run Code

Output:

7 5 8 6

Python


Download  Run Code

Output:

7 5 8 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 top view of a binary tree.