Top View

Problem

Intution

If we carefully observe the above picture, we can understand that, the top view of binary tree is the first node in at every horizontal distance.

Perform horizontal BFS traversal and update the value of map only when you encounter the horizontal distance for the first time.

This can be acheived using map.putIfAbsent()

Time Complexity

O(V+E) -> Standard BFS time complexity

Space Complexity

O(K)

k-> maximum number of horizontal distances

Code

Last updated