Output: [5, 10, 4, 28, 25] Explanation: Here, 14 and 28 both have horizontal distance = 1 from root, but we are taking 28 in our answer as 28 appears later in the level order traversal.
[Expected Approach - 1] Using DFS - O(n) Time and O(n) Space
The idea is to create a hashmap to store the horizontal distance and the bottom-most node having that horizontal distance wrt root node. During DFS, if we encounter a node whose horizontal distance is not present in the map, add it to the map. If we encounter a node whose horizontal distance already exists as a key in the map:
Choose the node with greater depth.
If both nodes have the same depth, choose the current node, because it appears later in level order traversal.
Output
5 10 4 28 25
[Expected Approach - 2] Using BFS - O(n) Time and O(n) Space
The idea is to do BFS while maintaining a map for horizontal distance (key) and the last node (value). The value for a certain distance is updated as we progress in the level order traversal.