Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
One idea can be do a level order traversal with the range and storing the data for the range in the map that comes first. Other can be to store the track of range and depth during traversal along with map.
The idea is to create a map keyed on the range (horizontal distance from root). We add or update if the depth is less than the current stored element.
You've successfully subscribed to Coding Today
Great! Next, complete checkout for full access to Coding Today
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.