Balanced Binary Tree solution explained
To check whether a binary tree is height-balanced, compute heights bottom-up and fail fast: a helper returns a subtree's height, or a sentinel such as -1 the moment any node below has children whose heights differ by more than one. The tree is balanced if the root's call does not return the sentinel. That visits each node once, O(n) time.
By Evin JohnPublished 7 min read
The rule being checked
A binary tree is height-balanced when every node, not only the root, has left and right subtrees whose heights differ by zero or one. An empty subtree has height zero. Given the root, return true if the whole tree meets that rule and false otherwise. An empty tree is balanced.
10 10
/ \ / \
5 15 5 15
/ \ / \ \
3 20 3 7 20
/ \
1 25
not balanced balancedIn the left tree the root's subtrees both have height 3, so a root-only check passes. Node 5, though, has a left subtree of height 2 and no right subtree, a gap of two. Node 15 has the same problem on the other side. The right tree passes at every node. A chain of three nodes leaning one way also fails, at its top node.
Why it is asked
Balanced trees matter in practice: search trees stay fast only while their height stays near log n, and self-balancing structures such as AVL trees enforce this very rule. In an interview the problem is shorter than its background. It checks whether you can avoid recomputing heights, and whether you can carry two pieces of information, "how tall" and "still balanced", up a recursion without making the code messy.
Top-down: ask for heights at every node
The direct translation of the rule: at each node, compute the height of both children with a helper, compare them, then check both children the same way. It is correct and easy to explain, but the height helper walks the whole subtree each time. For a balanced tree that totals O(n log n). For a chain it is O(n²), and the chain is exactly the shape that answers false, so the code is slowest when the answer is simplest.
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
def is_balanced_slow(node):
if node is None:
return True
if abs(height(node.left) - height(node.right)) > 1:
return False
return is_balanced_slow(node.left) and is_balanced_slow(node.right)Bottom-up with a sentinel
Turn it around. Compute each subtree's height once, from the leaves up, and check the balance rule at the same moment. If a subtree is already unbalanced, its exact height no longer matters, so return a value that cannot be a real height, such as -1. Any parent that receives -1 passes it straight up without doing more work. Checking the left result before recursing to the right adds a further early exit.
UNEVEN = -1
def is_balanced(root):
def checked_height(node):
if node is None:
return 0
left = checked_height(node.left)
if left == UNEVEN:
return UNEVEN
right = checked_height(node.right)
if right == UNEVEN or abs(left - right) > 1:
return UNEVEN
return 1 + max(left, right)
return checked_height(root) != UNEVEN#include <algorithm>
#include <cstdlib>
struct TreeNode {
int val;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
explicit TreeNode(int v) : val(v) {}
};
// Height of the subtree, or -1 as soon as any node below is uneven.
int checkedHeight(const TreeNode* node) {
if (node == nullptr) return 0;
int left = checkedHeight(node->left);
if (left < 0) return -1;
int right = checkedHeight(node->right);
if (right < 0 || std::abs(left - right) > 1) return -1;
return 1 + std::max(left, right);
}
bool isBalanced(const TreeNode* root) {
return checkedHeight(root) >= 0;
}A sentinel keeps the helper's signature simple. If you find it too clever, return a pair of (balanced, height) instead; the logic is identical and some interviewers find it easier to read. In languages with exceptions, throwing on the first imbalance and catching at the top also works, though it is less common in interview code.
Trace on the failing tree
Leaf 1 returns 1. Node 3 sees 1 and 0, returns 2. Node 5 sees 2 on the left and 0 on the right, a gap of two, so it returns -1. The root receives -1 from its left call and returns -1 at once, without looking at the right subtree at all. The final answer is false.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Top-down with height calls | O(n log n) balanced, O(n²) on a chain | O(h) recursion |
| Bottom-up with a sentinel | O(n), often less with early exit | O(h) recursion |
| Iterative post-order with stored heights | O(n) | O(n) for the stack and the height map |
Cases to check
- Empty tree and a single node: both balanced.
- Root with one child: balanced, since the gap is one.
- A chain of three: not balanced at the top node.
- Imbalance hidden below a root whose two sides are equal, like the left drawing.
- A complete tree with the last level partly filled: balanced.
Mistakes that come up
- Comparing heights only at the root.
- Confusing balanced with complete or full. A balanced tree can have gaps anywhere, as long as no gap exceeds one level at any node.
- Using the minimum depth and maximum depth of leaves and requiring them to differ by at most one. That rule is stricter than height-balanced and rejects some balanced trees.
- Forgetting to propagate the sentinel, so a -1 from below gets turned into a normal-looking height by the max.
Follow-ups
- Make an unbalanced search tree balanced. Read its values in order into a sorted list, then rebuild by picking the middle element as the root recursively.
- Keep it balanced under inserts. That is what AVL and red-black trees do with rotations; describe the idea, not the full code.
- Report the first unbalanced node. Return it alongside the sentinel, or record it in a side variable when the gap is found.
- A different tolerance. Replace the one with a parameter k; nothing else changes.
Explaining it
Fictional example
- Candidate
- The rule applies at every node, so checking the root isn't enough. Computing heights separately at each node repeats work, up to quadratic on a chain.
- Candidate
- I'll compute heights bottom-up once. If a node's children differ by more than one, I return -1, and any parent that sees -1 returns -1 too.
- Candidate
- That's one visit per node, O(n), and it stops early on the first imbalance on the left side.
Related walkthroughs
Diameter of Binary Tree uses the same height helper but tracks a maximum instead of a flag. Validate Binary Search Tree checks a different rule that also has to hold at every node, and Same Tree compares two trees node by node. Browse the rest on the coding problems hub.
Natively in practice sessions
On a Mac or Windows PC, Natively can read a balanced-tree prompt and its drawing from a screenshot while you practice, then suggest the bottom-up approach and the hidden-imbalance case worth testing. Your mock is transcribed alongside notes, which helps when you want to reread how you explained the sentinel. The AI interview assistant page has the details.
Questions people ask
How do you check if a binary tree is balanced?
Compute heights bottom-up with a helper that returns -1 as soon as any node's left and right heights differ by more than one. Parents pass -1 straight up. The tree is balanced if the root's call is not -1. This is O(n).
Why is the top-down balanced tree check slow?
It calls a separate height function at every node, so subtrees are measured again and again. That is O(n log n) on a balanced tree and O(n squared) on a chain.
What does height-balanced mean?
At every node, the heights of the left and right subtrees differ by at most one. The rule applies to all nodes, not only the root.
Is a balanced binary tree the same as a complete binary tree?
No. A complete tree fills every level left to right except possibly the last. A balanced tree only limits the height difference at each node, so it can have gaps a complete tree cannot.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
