Skip to content

Instantly share code, notes, and snippets.

@yoniLavi
Created April 28, 2021 23:15
Show Gist options
  • Select an option

  • Save yoniLavi/04a12d6899b5cfc2ff4e3c80109e9e22 to your computer and use it in GitHub Desktop.

Select an option

Save yoniLavi/04a12d6899b5cfc2ff4e3c80109e9e22 to your computer and use it in GitHub Desktop.
Tree traversal using a generator
#!/usr/bin/env python3
tree = {
"name": '1', "children": [
{"name": '11', "children": [
{"name": '111', "children": [
{"name": '1111', "children": []},
]},
{"name": '112', "children": []},
]},
{"name": '12', "children": [
{"name": '121', "children": []},
]},
]
}
def descender(node, depth=-1):
"""Traverse a tree depth-first up to `depth` levels`"""
if not depth:
return
yield node
for child in node["children"]:
yield from descender(child, depth - 1)
if __name__ == '__main__':
for node in descender(tree, depth=3):
print(node["name"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment