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 assume one recent update has change the code and answer for python 3.
The desired output has changed from only the nodes on the 'single-direction-branches' to all the nodes you can see from the top, thus a lot of the posted codes is not valid.
I'm not sure if I can optimize the while part of my code, and I would prefer a version without recursion in python, but the code below is all I can post at the moment.
deftopView(root):# deal with empty tree caseifroot==None:return# tuple (pos, lvl, node.info)tupleList=[(0,0,root.info)]tupleAppend(tupleList,root.left,0,0,'L')tupleAppend(tupleList,root.right,0,0,'R')# select tuples with lowest lvl for each postupleList.sort(key=lambdatup:(tup[0],tup[1]))i=0whilei<len(tupleList)-1:whiletupleList[i][0]==tupleList[i+1][0]:tupleList.pop(i+1)if(i+1)>len(tupleList)-1:breaki+=1for_,_,dataintupleList:print(data,end=" ")deftupleAppend(ls,node,pos,lvl,direction):ifnode:ifdirection=='L':pos=pos-1elifdirection=='R':pos=pos+1lvl=lvl+1ls.append((pos,lvl,node.info))tupleAppend(ls,node.left,pos,lvl,'L')tupleAppend(ls,node.right,pos,lvl,'R')
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 →