Balanced Binary Tree
Check that at every node the two subtree heights differ by at most 1, in one bottom-up pass.
The problem
You get the root of a binary tree. The tree is height-balanced if, at every node, the heights of the left and right subtrees differ by at most 1. Return true if the tree is height-balanced and false otherwise; an empty tree counts as balanced.
Input root = [10, 5, 15, 3, 7, null, 20]
Output true
Both sides of the root have height 2, and every other node's sides differ by at most 1.
Input root = [1, 2, 3, 4, null, null, 5, 6, null, null, 7]
Output false
The root looks fine, with height 3 on both sides, but node 2 has a left side of height 2 and no right side.
How to spot the pattern
- The rule has to hold at every node, not just at the root.
- Judging a node needs its children's heights, which a post-order DFS computes on the way up.
The idea
To judge a node you need the heights of its two subtrees, and those come from its children. So compute heights bottom-up, and let a subtree report -1 as soon as it finds an imbalance anywhere inside it. That -1 travels straight up to the root, so the whole check takes one pass.
Brute force: At every node, call a separate height function on both children, which measures the same subtrees again and again and takes O(n^2) time on a skewed tree.
Step by step
- 1Write a helper that returns a subtree's height, or -1 if the subtree is not balanced.
- 2For an empty node, return 0.
- 3Get the left height and the right height, and return -1 at once if either one is -1.
- 4If the two heights differ by more than 1, return -1.
- 5Otherwise return
1 + max(left, right); the tree is balanced when the call on the root does not return -1.
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(node: Optional[TreeNode]) -> int:
# The subtree's height, or -1 if it is not balanced.
if node is None:
return 0
left = height(node.left)
if left == -1:
return -1
right = height(node.right)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
return 1 + max(left, right)
return height(root) != -1Complexity
Time
O(n)
Space
O(h)
Each node's height is computed once and a -1 stops the work early; the stack grows to the tree's height h.
Watch out for
- Checking only the root: both sides of the root can have the same height while a node lower down is badly unbalanced.
- Mixing up balanced with complete: a balanced tree can have gaps, as long as no node's sides differ in height by more than 1.
Follow-up questions
How would you rebalance an unbalanced BST?
Read its values in sorted order with an in-order traversal, then build a new tree by always picking the middle value as the root, as in Convert Sorted Array to Binary Search Tree.
Why use -1 instead of returning a (height, balanced) pair?
A real height is never negative, so -1 can't be mistaken for one. A pair works just as well and some people find it clearer.
In Hinglish
Neeche se upar height bhejo, aur jaise hi kisi node par dono taraf ki height mein 1 se zyada farak mile, -1 bhej do. Root tak -1 pahuncha toh tree balanced nahi hai.