Skip to content

Instantly share code, notes, and snippets.

@Khamies
Last active March 19, 2023 07:00
Show Gist options
  • Select an option

  • Save Khamies/7ffc40dea05540119c328e47301a571f to your computer and use it in GitHub Desktop.

Select an option

Save Khamies/7ffc40dea05540119c328e47301a571f to your computer and use it in GitHub Desktop.
def is_balanced_BT(root):
def check_balance(root):
if not root:
return [True, 0]
left_height_component = check_balance(root.left)
right_height_component = check_balance(root.right)
balanced_childs = left_height_component[0] and right_height_component[0]
difference = abs(left_height_component[1] - right_height_component[1])
balanced_parent = difference <= 1
balanced = balanced_childs and balanced_parent
return (balanced, max(left_height_component[1], right_height_component[1]) + 1)
if not root:
return True
is_balanced_tree = check_balance(root)[0]
return is_balanced_tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment