110. Balanced Binary Tree
## description
## 110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
Example 1:
1Input: root = [3,9,20,null,null,15,7]
2Output: trueExample 2:
1Input: root = [1,2,2,3,3,null,null,4,4]
2Output: falseExample 3:
1Input: root = []
2Output: true- –The number of nodes in the tree is in the range [0, 5000].
- –-104 <= Node.val <= 104
Constraints:
## notes
### Intuition
A tree is balanced if the depth difference between left and right subtrees never exceeds 1 at any node. We can combine the balance check with height calculation by using a sentinel value (-1) to propagate imbalance upward.
### Implementation
Use a recursive DFS function that returns the height of a subtree, or -1 if it's unbalanced. Base case: null node returns 0. Recurse on the left subtree—if it returns -1, immediately propagate -1 upward. Do the same for the right subtree. If both subtrees are balanced, check if their height difference exceeds 1; if so, return -1. Otherwise, return 1 + max(left, right). In the main function, the tree is balanced if DFS doesn't return -1.
### Edge-cases
An empty tree is considered balanced (returns height 0).
- –Time: O(n) — visit each node once
- –Space: O(h) — recursion stack depth equals tree height
### Complexity
## solution
1from typing import Optional
2from lcutils import TreeNode
3
4# Definition for a binary tree node.
5# class TreeNode:
6# def __init__(self, val=0, left=None, right=None):
7# self.val = val
8# self.left = left
9# self.right = right
10class Solution:
11 def isBalanced(self, root: Optional[TreeNode]) -> bool:
12 def height(root: Optional[TreeNode]) -> int:
13 if not root:
14 return 0
15
16 lh = height(root.left)
17 if lh == -1:
18 return -1
19
20 rh = height(root.right)
21 if rh == -1:
22 return -1
23
24 if abs(lh - rh) > 1:
25 return -1
26
27 return 1 + max(lh, rh)
28
29 return height(root) != -1
30
31
32
33
34if __name__ == "__main__":
35 # Include one-off tests here or debugging logic that can be run by running this file
36 # e.g. print(solution.two_sum([1, 2, 3, 4], 3))
37 solution = Solution()
38