We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def topView(root):
res = ''
from collections import defaultdict
queue=[(root,0)]
hashtable=defaultdict(lambda:[])
for node,level in queue: #level=x-coordinator
if node!=None:
hashtable[level].append(node.info) #hashtable, collect node data with the same level
queue.extend([(node.left,level-1),(node.right,level+1)]) #add node in sublevel to queue
if hashtable !=None:
for level in range(min(hashtable.keys()),max(hashtable.keys())+1):
res += str(hashtable[level][0]) + ' '
print(res) #TOPVIEW
# print(' '.join(map(str, res)))
else:
return None
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
Updated for Python 3: