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.
def top_view(root: BinaryTreeNode) -> None:
if root is None:
return
# Dictionary to store the first node at each horizontal distance
top_view_map = {}
# List for level order traversal (acting as a queue)
queue = [(root, 0)] # (node, horizontal distance)
while queue:
# Pop the first element from the list
node, hd = queue[0] # Get the first element
queue = queue[1:] # Remove the first element
# If this is the first time we are visiting this horizontal distance
if hd not in top_view_map:
top_view_map[hd] = node.value
# Add left and right children to the queue with updated horizontal distances
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
# Sort the horizontal distances and print the corresponding node values
for hd in sorted(top_view_map.keys()):
print(top_view_map[hd], end=" ")
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 →
1 case failed, can you spot the bug?
Create the top_view method
def top_view(root: BinaryTreeNode) -> None: if root is None: return