Skip to content

Instantly share code, notes, and snippets.

@g0rdan
Created August 30, 2019 15:11
Show Gist options
  • Save g0rdan/d8469015291ea1b96f52fb4668a0a995 to your computer and use it in GitHub Desktop.
Save g0rdan/d8469015291ea1b96f52fb4668a0a995 to your computer and use it in GitHub Desktop.
Tree Top View on HackerRank.com
import queue
class NodeWrap:
def __init__(self, node, hd):
self.node = node
self.hd = hd
def topView(root):
d = {}
q = queue.Queue()
q.put(NodeWrap(root, 0))
while not q.empty():
node_wrap = q.get()
node = node_wrap.node
current_hd = node_wrap.hd
if d.get(current_hd) is None:
d[current_hd] = node
print(node.info, end=" ")
if node.left is not None:
q.put(NodeWrap(node.left, current_hd - 1))
if node.right is not None:
q.put(NodeWrap(node.right, current_hd + 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment