Determine whether every node in a binary tree has subtrees of nearly equal height.
Problem
Input. The root of a finite binary tree, with left and right child references or None.
Output. Return True exactly when every node’s left and right subtree heights differ by at most one.
Rules. Height counts nodes: an empty subtree has height zero and a leaf has height one. The condition must hold throughout the tree, not only at the root. Assume no cycles or shared children. Do not change any nodes; an empty tree is balanced.
Example. A root with two leaf children returns True.
A three-node chain containing only left children returns False; its root’s subtree heights are two and zero.
Picture
Follow the left chain upward. Valid heights stop at node 2; the root then skips its right subtree.
| Node | Left result | Right result | Returned result |
|---|---|---|---|
| 4 | 0 | 0 | 1 |
| 3 | 1 | 0 | 2 |
| 2 | 2 | 0 | -1: unbalanced |
| 1 | -1 | Not called | -1: propagate failure |
Problem trace
An unbalanced child can end the check before further searching
Reference drawing
Problem trace
An unbalanced child can end the check before further searching
Execution trace
- 1stack start
- 2stack
- 3stack
- 4current
- 3stack
- 5
- 6
- 7
- 2stack
- node 1
- stack start
- node 2
- stack
- node 3
- stack
- 1
- 2
- 3
- 4return height 1
- 3
- 5
- 6
- 7
- 2
- node 4
- current→return height 1
- node 1
- stack start→not shown
- node 2
- stack→not shown
- 1
- 2
- 3return height 2
- 4left height 1
- 3return height 2
- 5
- 6
- 7
- 2
- node 3
- not shown→return height 2
- node 4
- return height 1→left height 1
- arithmetic
- |0-0| = 0 <= 1; 1 + max(0,0) = 1→|1-0| = 1; 1 + max(1,0) = 2
- 1
- 2return -1
- 3left height 2
- 4
- 3left height 2
- 5
- 6
- 7
- 2return -1
- node 2
- not shown→return -1
- node 3
- return height 2→left height 2
- node 4
- left height 1→not shown
- 1propagate -1
- 2left returned -1
- 3
- 4
- 3
- 5skipped
- 6skipped
- 7skipped
- 2left returned -1
- node 1
- not shown→propagate -1
- node 2
- return -1→left returned -1
- node 5
- not shown→skipped
- 1height(root) = -1
- 2
- 3
- 4
- 3
- 5
- 6
- 7
- 2
- node 1
- propagate -1→height(root) = -1
- node 2
- left returned -1→not shown
- node 5
- skipped→not shown
- Recognize it
- Use a sentinel summary when a parent needs a normal child aggregate but any descendant failure should abort remaining work, as in balanced-height checks or invalid-subtree detection.
- Keep true
- height(node) returns the exact nonnegative subtree height if every node below is balanced; otherwise it returns -1. Thus ancestors can distinguish valid data from failure without a second traversal.
- Reuse it
- Fuse a subtree summary with validation by reserving an impossible summary value for failure, then check it before doing more recursion; this generalizes to BST validation and parse-tree error propagation.
Root-only testing fails here. Its child heights are three and two, only one apart; node 2 still violates the condition.
Code
Use this node type for a local run.
from dataclasses import dataclass
@dataclass
class TreeNode:
val: int
left: "TreeNode | None" = None
right: "TreeNode | None" = None
def is_balanced(root: TreeNode | None) -> bool:
def height(node: TreeNode | None) -> int:
if node is None:
return 0
left = height(node.left)
if left < 0:
return -1
right = height(node.right)
if right < 0 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return height(root) >= 0
Extend the Returned Contract
A nonnegative return is the exact height. It also certifies balance everywhere in that subtree.
The value -1 means failure, not another height.
Every legitimate height is nonnegative, so this sentinel cannot collide with valid data.
Check left failure before calling right. Then check right failure and the local difference before returning a height.
Both certified children and an acceptable local difference are necessary. Ignoring a descendant’s failure loses the whole-tree guarantee.
Each visited node does constant work: worst-case time and call-stack space for height .
Recomputing heights separately at every node can take quadratic time along a chain. Deep trees can exceed Python’s recursion limit.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why propagate failure before combining heights? A failed child has no certified height in this interface.
Keep Height Even on Failure
Choose this when: The caller needs the actual height of an unbalanced tree too.
Return height and validity separately. Visit both children even when one is unbalanced; otherwise the requested height could be wrong.
def height_and_balance(root):
if root is None:
return [0, True]
left_height, left_ok = height_and_balance(root.left)
right_height, right_ok = height_and_balance(root.right)
return [
1 + max(left_height, right_height),
left_ok and right_ok and abs(left_height - right_height) <= 1,
]
A three-node one-sided chain returns [3, False]; an empty tree returns [0, True].
Unlike the sentinel version, this interface preserves the aggregate after validation fails. It visits all nodes in time and retains stack space.
Change the Allowed Difference
Choose this when: Every local height difference may be at most a supplied nonnegative tolerance.
def balanced_with_tolerance(root, tolerance):
if tolerance < 0:
raise ValueError("nonnegative tolerance required")
def height(node):
if node is None:
return 0
left = height(node.left)
if left < 0:
return -1
right = height(node.right)
if right < 0 or abs(left - right) > tolerance:
return -1
return 1 + max(left, right)
return height(root) >= 0
The same three-node chain passes tolerance two and fails tolerance one. Zero requires equal child heights at every node. Negative tolerance raises ValueError, including for an empty tree.
Only the local threshold changes. Every descendant must still pass. Worst-case time remains and stack space .
Transfer
A failure sentinel is useful only while it cannot be mistaken for a valid summary. If callers need the summary after failure, return validity separately instead of discarding it.