Given a root of a binary tree, print the top view of a binary tree

This problem is similar to the vertical order traversal of the binary tree. The only catch is here is that , when we are storing the level wise elements in the hashmap , we check if there is already a value exists in the hashmap for that level. If it exists, we wouldn't storing again at that level because as we are coming from the top (root), the first element at each level is what appears in the output.

class TreeNode():
def __init__(self,val):
self.val = val
self.left = None
self.right = None

class solution():
def topview(self,root):
if not root:
return []
hmap ={}
minlevel=2**31-1
maxlevel = -2**31
q = [(root,0)]

while q:
(node,level) = q.pop(0)

if level not in hmap:
hmap[level] = node.val

minlevel = min(minlevel,level)
maxlevel = max(maxlevel,level)

if node.left:
q.append((node.left,level-1))

if node.right:
q.append((node.right,level+1))
res = []

for level in range(minlevel,maxlevel+1):
res.append(hmap[level])

return res

def main():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(9)
root.left.right = TreeNode(3)
root.left.right.left = TreeNode(4)
root.left.right.left.left = TreeNode(5)
root.right.left = TreeNode(6)
root.right.left.right = TreeNode(7)

print solution().topview(root)

if __name__=='__main__':
main()