Difficulty: Easy
https://leetcode.com/problems/balanced-binary-tree/
The code is shown below:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def getHeight(root):
if not root:
return 0
return max(getHeight(root.left), getHeight(root.right)) + 1
if not root:
return True
left_height, right_height = getHeight(root.left), getHeight(root.right)
diff = abs(left_height - right_height)
return diff <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)