Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created February 12, 2018 06:06
Show Gist options
  • Save izmailoff/7a4b5462b061d284430f37ef465b7a92 to your computer and use it in GitHub Desktop.
Save izmailoff/7a4b5462b061d284430f37ef465b7a92 to your computer and use it in GitHub Desktop.
A function that checks if binary tree is balanced
def height_min_max(tree):
if not tree:
return 0, 0
else:
_, l, r = tree
lmin, lmax = height_min_max(l)
rmin, rmax = height_min_max(r)
return 1 + min(lmin, rmin), 1 + max(lmax, rmax)
def is_balanced(tree):
tmin, tmax = height_min_max(tree)
return tmax - tmin <= 1
@izmailoff
Copy link
Author

Test in Python REPL:

>>> balanced = (1, (2, (3, None, None), (4, None, None)), (5, None, None))

>>> height_min_max(balanced)
(2, 3)

>>> is_balanced(balanced)
True

>>> unbalanced = (1, (2, (3, None, None), (4, (6, None, None), None)), (5, None, None))

>>> is_balanced(unbalanced)
False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment