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.
I am a beginner. If I found this place earlier, I would have not spent hours on this unclarified 'easy' question and doubt myself......
In conclusion, two interpretations on this question:
1. Just like what @thedurphy said, this interpretation of top view aligns with this Youtube video and GFG. And code in Python can be like this (Although it does not pass all tests, it aligns with first interpretation):
deftopView(root):fromcollectionsimportdefaultdictqueue=[(root,0)]hashtable=defaultdict(lambda:[])fornode,levelinqueue:#level=x-coordinatorifnode!=None:hashtable[level].append(node.data)#hashtable, collect node data with the same level#queue.extend([(node.left,level-1),(node.right,level+1)])#add node in sublevel to queueifhashtable!=None:forlevelinxrange(min(hashtable.keys()),max(hashtable.keys())+1):printhashtable[level][0],#TOPVIEWelse:returnNone
Another interpretation is provided by @trideceth12, which is aligned with all test cases. Although I doubt this interpretation, I still created the Python code for it:
deftopView(root):#start with left most leafifroot.left:printleftside(root.left)#print left side top view, from bottom to top (left to right)printroot.data,#print rootifroot.right:printrightside(root.right)#print right side top view, from top to bottom (left to right)defprintleftside(node):ifnode:printleftside(node.left)else:returnprintnode.data,defprintrightside(node):ifnode:printnode.data,printrightside(node.right)else:return
In the end, WHAT do we use TOPVIEW for in terms of both interpretations?
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
I am a beginner. If I found this place earlier, I would have not spent hours on this unclarified 'easy' question and doubt myself...... In conclusion, two interpretations on this question: 1. Just like what @thedurphy said, this interpretation of top view aligns with this Youtube video and GFG. And code in Python can be like this (Although it does not pass all tests, it aligns with first interpretation):
In the end, WHAT do we use TOPVIEW for in terms of both interpretations?