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.

- Prepare
- Data Structures
- Trees
- Tree : Top View
- Discussions

# Tree : Top View

# Tree : Top View

#### Sort by

recency

#### |

#### 937 Discussions

#### |

Please Login in order to post a comment

THIS QUESTION IS SO F BAD. It's not like it's hard but the problem is so poorly explained and the test cases are so illy created.

I at first thought it's just all the left most nodes and right most nodes are visible from top view, it also satisifies the test case presented and fit the problem difficulty. But no, so I had to search up the definition of top view which turns out is horizontal distance corresponds to the node parent. Thats also bearable, just need to keep track of parent distance and visited distance, not too bad.

BUT HOW CAN YOU NOT ALLOW DIFFERENT PERMUTATION OF THE ANSWER?!

so i had to guess it's sorted by the distance and store them in hashmap... sigh

if your tests are failig, then you could try with this - test data 4: 50 47 2 40 20 38 30 14 28 10 16 19 44 39 27 7 9 31 12 43 21 5 41 34 49 13 33 3 4 25 22 29 15 32 35 6 24 23 26 1 11 42 36 37 17 18 8 45 48 50 46

easy peasy

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.