Skip to content

Instantly share code, notes, and snippets.

@Poorvak
Created January 7, 2019 04:32
Show Gist options
  • Save Poorvak/d870f170a238c708cc907dd4b8d25943 to your computer and use it in GitHub Desktop.
Save Poorvak/d870f170a238c708cc907dd4b8d25943 to your computer and use it in GitHub Desktop.
How to determine if a binary tree is height-balanced?
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def get_height(root: Node) -> int:
if root is None:
return 0
return max(get_height(root.left), get_height(root.right)) + 1
def check_if_balanced(root: Node) -> bool:
if root is None:
return True
lft_height = get_height(root.left)
rt_height = get_height(root.right)
if (abs(lft_height - rt_height) <= 1) and check_if_balanced(root.left) and check_if_balanced(root.right):
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment