Answer
See the explanation
Work Step by Step
Here's a Python function to check if a binary tree is balanced:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def is_balanced(root):
if root is None:
return True
left_height = height(root.left)
right_height = height(root.right)
if abs(left_height - right_height) <= 1 and is_balanced(root.left) and is_balanced(root.right):
return True
return False
```
This function defines a `TreeNode` class to represent nodes in the binary tree. The `height` function calculates the height of a given node recursively. The `is_balanced` function checks if a binary tree is balanced by comparing the heights of its left and right subtrees recursively. If the absolute difference in heights is less than or equal to 1 and both subtrees are balanced, then the tree is considered balanced.