def isBalanced(root: Optional[TreeNode]) -> bool:
def helper(root):
# if root is None hence the depth is 0 and it is balanced
if not root:
return(True, 0)
else:
balanced_left, depth_left = helper(root.left) # first check left subtree
# if left subtree is not balanced, no need to check right subtree
if not balanced_left:
return(False, depth_left + 1)
balanced_right, depth_right = helper(root.right) # check right subtree
# current tree is balanced if right (and left) subtree are balanced and their depth are not different by more than 1
return(balanced_right and (abs(depth_left-depth_right)<=1), max(depth_left, depth_right) + 1)
return(helper(root)[0])