Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Created September 9, 2021 05:23
Show Gist options
  • Save ssshukla26/ace6e7a63662f91637fed7b063ba9ffb to your computer and use it in GitHub Desktop.
Save ssshukla26/ace6e7a63662f91637fed7b063ba9ffb to your computer and use it in GitHub Desktop.
Function to return path from root to a target node in a binary tree
# A function which returns path from root to the given target
def getPath(curr, target, path: List):
# if current node is not none
if curr:
# Add current node to the path
path.append(curr)
# if current node is target return path
if curr == target:
return path
# If target is found in the left subtree, return path
if getPath(curr.left, target, path):
return path
# If target is found in the right subtree, return path
if getPath(curr.right, target, path):
return path
# remove current node from the path
path.remove(curr)
return None # by default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment