Created
October 21, 2019 17:43
-
-
Save biancarosa/bf27ef9105b29d1c0c445db12a582e99 to your computer and use it in GitHub Desktop.
top view algorithm to solve https://www.hackerrank.com/challenges/tree-top-view/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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