Skip to content

Instantly share code, notes, and snippets.

@biancarosa
Created October 21, 2019 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biancarosa/bf27ef9105b29d1c0c445db12a582e99 to your computer and use it in GitHub Desktop.
Save biancarosa/bf27ef9105b29d1c0c445db12a582e99 to your computer and use it in GitHub Desktop.
def topView(root):
queue = deque([])
VerticallyDistantNode = namedtuple('VerticallyDistantNode', 'node distance')
queue.append(VerticallyDistantNode(root, 0))
distance_map = {}
while (len(queue) > 0):
node, distance = queue.popleft()
if distance_map.get(distance) is None:
distance_map[distance] = node
if (node.left):
queue.append(VerticallyDistantNode(node.left, distance - 1))
if (node.right):
queue.append(VerticallyDistantNode(node.right, distance + 1))
for i in sorted(distance_map.keys()):
print(distance_map[i].info, end=' ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment