Created
November 14, 2020 09:59
-
-
Save justbuchanan/8d76f25e9c68b501556f76c433c22514 to your computer and use it in GitHub Desktop.
recursive tree-building in python
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
# Creates a binary tree of depth `d`. Each node is represented as a python `dict`, | |
# with the value of the key "leaf" as a boolean indicating whether or not the node is a leaf node. | |
def make_tree(d): | |
assert d > 0 | |
if d == 1: return {"leaf": True} | |
else: return {"leaf": False, "left": make_tree(d-1), "right": make_tree(d-1)} | |
make_tree(1) | |
# {'leaf': True} | |
make_tree(2) | |
# {'leaf': False, | |
# 'left': {'leaf': True}, | |
# 'right': {'leaf': True}} | |
make_tree(3) | |
# {'leaf': False, | |
# 'left': {'leaf': False, | |
# 'left': {'leaf': True}, | |
# 'right': {'leaf': True}}, | |
# 'right': {'leaf': False, | |
# 'left': {'leaf': True}, | |
# 'right': {'leaf': True}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment