Created
April 28, 2021 23:15
-
-
Save yoniLavi/04a12d6899b5cfc2ff4e3c80109e9e22 to your computer and use it in GitHub Desktop.
Tree traversal using a generator
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
| #!/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