Created
January 13, 2018 01:52
-
-
Save pdarche/24a870fb54ea756af3bc308c7fddfd19 to your computer and use it in GitHub Desktop.
Finds a node in a tree using depth first search
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
| """ | |
| Depth first search code for the Recurse Center! | |
| """ | |
| def search_tree(tree, node, target_node): | |
| """ Finds a node in a tree using depth first search """ | |
| if node == target_node: | |
| return target_node | |
| for child_node in tree[node]: | |
| found_node = search_tree(tree, child_node, target_node) | |
| if found_node: | |
| return found_node | |
| if __name__ == '__main__': | |
| tree = { | |
| 'a': ['b', 'c'], | |
| 'b': ['d', 'e', 'f'], | |
| 'c': ['g'], | |
| 'd': [], | |
| 'e': [], | |
| 'f': [], | |
| 'g': ['h'], | |
| 'h': [] | |
| } | |
| output = search_tree(tree, 'a', 'g') | |
| print(output) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment