Created
February 12, 2018 06:06
-
-
Save izmailoff/7a4b5462b061d284430f37ef465b7a92 to your computer and use it in GitHub Desktop.
A function that checks if binary tree is balanced
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
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test in Python REPL: