Created
September 9, 2021 05:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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