Created
August 30, 2019 15:11
-
-
Save g0rdan/d8469015291ea1b96f52fb4668a0a995 to your computer and use it in GitHub Desktop.
Tree Top View on HackerRank.com
This file contains hidden or 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
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