Created
January 7, 2019 04:32
-
-
Save Poorvak/d870f170a238c708cc907dd4b8d25943 to your computer and use it in GitHub Desktop.
How to determine if a binary tree is height-balanced?
This file contains 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
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