Balanced Binary Tree
Pattern: Depth, diameter and balance
A tree is balanced when, at every node, the heights of the two subtrees differ by at most 1. Compute heights bottom up and return -1 as soon as some subtree is unbalanced, so one pass answers both.
The problem
Return whether the tree is height-balanced: at every node, the left and right subtree heights differ by at most 1.
[3, 9, 20, null, null, 15, 7] is true; [1, 2, 2, 3, 3, null, null, 4, 4] is false. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Is checking only the root enough?
- What is wrong with calling height() at every node?
- How can one function report both a height and a failure?
Hints
Brute force, and why it fails
Call a separate height function at every node: O(n²) in the worst case.
The key insight
The post-order height already visits every node with its children's heights in hand, so the check costs nothing extra.
Dry run
| height(3) | 2 |
|---|
[1, 2, 2, 3, 3, null, null, 4, 4]. The two 4s are leaves: height 1. The 3 above them: height 2.
The plan
h(n): if null: 0
l = h(left); if l == -1: return -1
r = h(right); if r == -1 or |l - r| > 1: return -1
return 1 + max(l, r)
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- Empty tree.
- One node.
- A long chain, where recursion is n deep.
I've built my logic, show the code
Java
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode n) { // the height, or -1 as soon as some subtree is unbalanced
if (n == null) return 0;
int l = height(n.left);
if (l == -1) return -1;
int r = height(n.right);
if (r == -1 || Math.abs(l - r) > 1) return -1;
return 1 + Math.max(l, r);
}
}C++
class Solution {
public:
bool isBalanced(TreeNode* root) {
return height(root) != -1;
}
int height(TreeNode* n) { // the height, or -1 as soon as some subtree is unbalanced
if (n == NULL) return 0;
int l = height(n->left);
if (l == -1) return -1;
int r = height(n->right);
if (r == -1 || abs(l - r) > 1) return -1;
return 1 + max(l, r);
}
};Python
class Solution:
def isBalanced(self, root) -> bool:
def height(n) -> int: # the height, or -1 as soon as some subtree is unbalanced
if not n:
return 0
l = height(n.left)
if l == -1:
return -1
r = height(n.right)
if r == -1 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
return height(root) != -1Common mistakes
- Checking the rule only at the root.
- Recomputing heights for every node.