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 ={}
    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:

    if node.right:
    res = []

    for level in range(minlevel,maxlevel+1):

    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__':