Skip to content

Instantly share code, notes, and snippets.

@justbuchanan
Created November 14, 2020 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justbuchanan/8d76f25e9c68b501556f76c433c22514 to your computer and use it in GitHub Desktop.
Save justbuchanan/8d76f25e9c68b501556f76c433c22514 to your computer and use it in GitHub Desktop.
recursive tree-building in python
# 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