Skip to content

Instantly share code, notes, and snippets.

@pdarche
Created January 13, 2018 01:52
Show Gist options
  • Save pdarche/24a870fb54ea756af3bc308c7fddfd19 to your computer and use it in GitHub Desktop.
Save pdarche/24a870fb54ea756af3bc308c7fddfd19 to your computer and use it in GitHub Desktop.
Finds a node in a tree using depth first search
"""
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