Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Input: root = [3,9,20,null,null,15,7]
- code
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def helper(root, isBalanced = True):
if not root:
return (-1, True) # height, isBalanced
left_height, left_balance = helper(root.left)
right_height, right_balance = helper(root.right)
height = 1 + max(left_height, right_height)
isBalanced = left_balance and right_balance and abs(left_height - right_height) <= 1
return (height, isBalanced)
return helper(root)[1]