Binary trees top view

If i want to get the top view of a tree ? how should i approach ?
As in the question {Tree top view} one test cases in failed.

Hi Abhishu
This problem falls under the category of Hashing.
Use a hashmap which stores the data element in each vertical line .

Write a recursive function which assigns each node a vertical line value i.e. root node gets value 0 , root’s right child gets value 1 and left child gets value -1.
Increment vertical level value by 1 if you call on a right child and decrement by 1 if you call on the left child.

For each vertical line value store its first occurence in the hashmap and then finally output the tree top view using the hashmap.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.