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.
Hi,
this seemed quite faster in a couple benchmark I ran.
The main difference is the usage of dictionaries (that probably can check for items faster than in your code, to check for existence) and the queue removal.
Also, the "node, score" assignation avoid some indexing I believe...
deftopView(root):# Initialize the levelthis_level=[(root,0)]scores={}whilethis_level:# Basically iterate over the nodes on a single levelfor_inrange(len(this_level)):node,score=this_level.pop(0)# Skip empty nodesifnotnode:continue# Store the score if it's a new one!ifscorenotinscores:scores[score]=node.info# Add the node children to the next levelthis_level.extend([(node.left,score-1),(node.right,score+1)])# Sort the scores and print their values # (By default the sort is on the tuple first element: the score)for_,valueinsorted(list(scores.items())):print(value,end=' ')
Good coding.
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 →
Hi, this seemed quite faster in a couple benchmark I ran. The main difference is the usage of dictionaries (that probably can check for items faster than in your code, to check for existence) and the queue removal. Also, the "node, score" assignation avoid some indexing I believe...
Good coding.