We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Solution Steps:
1 - Perform a level-order traversal of the tree.
2- Keep track of the horizontal distance of each node from the root. For the root node, the horizontal distance is 0. For the left child, the horizontal distance decreases by 1, and for the right child, it increases by 1.
3 - Use a map or a dictionary to store the nodes at each horizontal distance.
4 - Traverse the tree and update the map with the first node encountered at each horizontal distance.
5 - Finally, print the values of the nodes stored in the map.

Explanation:
- We traverse the tree level by level using a queue.
- At each level, we update the horizontal distance of each node and store the first encountered node at each horizontal distance in a dictionary.
- Finally, we print the nodes stored in the dictionary, which represent the top view of the tree.

Cookie support is required to access HackerRank

Seems like cookies are disabled on this browser, please enable them to open this website

## Tree : Top View

You are viewing a single comment's thread. Return to all comments →

Solution Steps: 1 - Perform a level-order traversal of the tree. 2- Keep track of the horizontal distance of each node from the root. For the root node, the horizontal distance is 0. For the left child, the horizontal distance decreases by 1, and for the right child, it increases by 1. 3 - Use a map or a dictionary to store the nodes at each horizontal distance. 4 - Traverse the tree and update the map with the first node encountered at each horizontal distance. 5 - Finally, print the values of the nodes stored in the map.

Explanation: - We traverse the tree level by level using a queue. - At each level, we update the horizontal distance of each node and store the first encountered node at each horizontal distance in a dictionary. - Finally, we print the nodes stored in the dictionary, which represent the top view of the tree.