Data Structures · Visualization
Binary Tree: Is Balanced
Binary Tree
A tree is height-balanced if, for every node, the heights of its left and right subtrees differ by no more than 1. Time: O(n) with the optimized bottom-up approach. Space: O(h) for the recursion stack.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Is Balanced
Binary TreeA tree is height-balanced if, for every node, the heights of its left and right subtrees differ by no more than 1. This check is done recursively from the bottom up: compute each subtree's height while simultaneously checking the balance condition, stopping early if any imbalance is found.
How Is Balanced Works
- If the current node is null, its height is 0 and it is balanced (base case).
- Recursively check the left subtree, getting its height and balance status.
- Recursively check the right subtree, getting its height and balance status.
- The current node is balanced only if both subtrees are balanced AND their heights differ by at most 1.
- Return the combined balance status upward.
Is Balanced Worked Example
Input: Tree: root(1) -> left(2) -> left(3); root -> right(4)
- Left subtree (rooted at 2) has height 2; right subtree (rooted at 4) has height 1
- Difference is 1, so root is balanced so far
- Check node 2: left child 3 (height 1), right child null (height 0) → difference 1, balanced
Output: true (the tree is balanced)
Press ▶ Run to watch it step by step.
def is_balanced(root):
def dfs(n):
if not n:
return 0
l = dfs(n.left)
r = dfs(n.right)
if l == -1 or r == -1 or abs(l - r) > 1:
return -1 # unbalanced
return 1 + max(l, r)
return dfs(root) != -1
# example: is balancedBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Is Balanced Time & Space Complexity
When to Use Is Balanced
- Validating self-balancing tree implementations like AVL trees
- Deciding when a tree needs rebalancing to keep operations fast
- A common interview question about combining recursion with early exits
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.