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.
defgetNode(llist,positionFromTail):deftraverse(head,n=0):# Stop recursion condition. Stop when there is no children (reached tail)ifhead.nextisNone:return(n,head.data)# Save max_depth and possible answer valuemax_depth,ans=traverse(head.next,n+1)# We will exit this part only when we reach max depth of the list# As we are traversing backwards (getting outside of the recursion)# we check our main condition for the position from the tailifmax_depth-positionFromTail==n:# If we meet the condition we return the valuereturn(max_depth,head.data)else:# If the condition is not met yet or has already been met# we return the possible answer and the depthreturn(max_depth,ans)# Return the answerreturntraverse(llist)[1]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Get Node Value
You are viewing a single comment's thread. Return to all comments →
Python recursion solution explained.