15% off all plans & roadmaps Use code
See plansBalanced Binary Tree
- LeetCode 110
- Easy
- Tree Traversal Patterns (DFS & BFS)
- Recursive Postorder Traversal
Updated
TL;DR: Decide whether every node in a binary tree has left and right subtree heights that differ by at most 1. Compute heights bottom-up with a postorder DFS and return -1 as soon as any node breaks the rule.
Problem
Given a binary tree, determine whether it is height-balanced. A tree is height-balanced when, for every node, the heights of its left and right subtrees differ by at most 1.
Example 1
Input: root = [3,9,20,null,null,15,7] Output: true
Example 2
Input: root = [1,2,2,3,3,null,null,4,4] Output: false
Example 3
Input: root = [] Output: true
Constraints
- The number of nodes in the tree is in the range
[0, 5000]. -10^4 <= Node.val <= 10^4
Constraints that matter
- n is at most 5000, so an O(n^2) top-down check does about 12.5 million height steps in a skewed tree. It passes, but an interviewer will still expect O(n).
- n can be 0, so an empty tree must return true and the code must handle a null root.
- A tree of 5000 nodes can be a single chain, so recursion depth can reach 5000. This matters for Python, whose default recursion limit is 1000.
- Node values range over -10^4 to 10^4 but play no role. Only the shape of the tree decides the answer.
- The rule applies to every node, not only the root, so one global height comparison is never enough.
Hints
Hint 1
The pattern is a recursive postorder traversal.
Hint 2
Translate the definition literally.
Solution
Intuition
The pattern is a recursive postorder traversal. A node's balance depends on the heights of its two subtrees, so you need both children's answers before you can judge the parent. Postorder gives you exactly that order: left, right, then the node itself.
Picture a chain of building inspectors who each report one number upward: their section's floor count if level, or a red card if not. The red card is the -1 sentinel, and any supervisor receiving one passes it upward unchanged, so the top sees it only if some section failed.
The slow way to use the definition is to ask for the height of each child at every node. Height itself is a full walk down the subtree. Doing that walk at every node repeats work, because a deep node gets measured again by each of its ancestors.
The fix is to ask each recursive call for two facts at once: the height of its subtree and whether that subtree is balanced. You can pack both into one integer. Return the real height when the subtree is balanced, and return -1 when it is not. Heights are never negative, so -1 cannot be confused with a real height.
Once any node returns -1, every ancestor passes it straight up without more work. The root then sees -1 if and only if some node in the tree broke the rule.
Worked example
Input: root = [3,9,20,null,null,15,7] Output: true Explanation: Node 3 has a left subtree of height 1 (only node 9) and a right subtree of height 2 (node 20 with children 15 and 7). The difference is 1. Node 20 has two children of height 1, and the leaves have two empty children. Every node passes, so the answer is true.
Approach 1: Brute force: height at every node
Translate the definition literally. For each node, compute the height of its left subtree and its right subtree with a separate recursive height function. If they differ by more than 1, return false. Otherwise ask the same question about both children.
This is correct because it checks every node against the exact rule in the statement. It is also easy to write from memory.
Steps
- Write
height(node): return 0 for null, else 1 + max(height(left), height(right)). - Write
check(node): return true for null. - At each node, compute
height(node.left)andheight(node.right). - If their absolute difference is greater than 1, return false.
- Otherwise return
check(node.left) and check(node.right). - Call
check(root)and return its result.
Dry run
Trace on [3,9,20,null,null,15,7].
check(3):height(9)= 1,height(20)= 2. Difference 1, so continue.check(9): both children are null, heights 0 and 0. Passes. Its null children return true.check(20):height(15)= 1,height(7)= 1. Difference 0, so continue.check(15)andcheck(7): heights 0 and 0. Both pass.
Every call returned true, so the final answer is true. Note that height(15) was computed once by node 20's check, and node 3 had already walked over it inside height(20). That repeated walking is the waste.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(h) |
Let n be the number of nodes and h the tree height. height on a subtree visits every node in it, and a node at depth d sits inside d ancestor subtrees, so it is visited about d times. In a chain of n nodes the total is about n * (n + 1) / 2, which is O(n^2). The recursion stack never holds more than the current path, so extra space is O(h), which is O(n) in the worst case.
PythonTested in our runner
from typing import List, Optional
import sys
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
sys.setrecursionlimit(20000)
def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
def check(node):
if not node:
return True
if abs(height(node.left) - height(node.right)) > 1:
return False
return check(node.left) and check(node.right)
return check(root)JavaTested in our runner
import java.util.*;
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.abs(height(root.left) - height(root.right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
}C++Tested in our runner
#include <algorithm>
#include <cstdlib>
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
if (std::abs(height(root->left) - height(root->right)) > 1) return false;
return isBalanced(root->left) && isBalanced(root->right);
}
private:
int height(TreeNode* node) {
if (node == nullptr) return 0;
return 1 + std::max(height(node->left), height(node->right));
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
const height = (node) => {
if (node === null) return 0;
return 1 + Math.max(height(node.left), height(node.right));
};
const check = (node) => {
if (node === null) return true;
if (Math.abs(height(node.left) - height(node.right)) > 1) return false;
return check(node.left) && check(node.right);
};
return check(root);
};GoTested in our runner
func bruteHeight(node *TreeNode) int {
if node == nil {
return 0
}
l, r := bruteHeight(node.Left), bruteHeight(node.Right)
if l > r {
return l + 1
}
return r + 1
}
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
diff := bruteHeight(root.Left) - bruteHeight(root.Right)
if diff > 1 || diff < -1 {
return false
}
return isBalanced(root.Left) && isBalanced(root.Right)
}C#Tested in our runner
public class Solution {
public bool isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.Abs(Height(root.left) - Height(root.right)) > 1) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
private int Height(TreeNode node) {
if (node == null) return 0;
return 1 + Math.Max(Height(node.left), Height(node.right));
}
}Approach 2: Top-down check with memoized heights
What's slow: the brute force recomputes the height of the same subtree many times. Node 20 in the example is measured once inside height(20) called from node 3, and again when check(20) runs. In a chain this repetition grows to n^2.
The insight that fixes it: a subtree's height never changes, so store it. Keep a map from node to height. The first call to height(node) does the walk and saves the result, and every later call is a lookup. This is dynamic programming over subtrees, with the node as the state.
Steps
- Create an empty map from node to height.
- Write
height(node): return 0 for null, return the stored value if present. - Otherwise compute 1 + max(height(left), height(right)), store it, and return it.
- Write
check(node)as in the brute force: null is balanced. - Compare the cached heights of both children and return false if they differ by more than 1.
- Otherwise return
check(left) and check(right).
Dry run
Trace on [3,9,20,null,null,15,7] with the cache starting empty.
check(3)asks forheight(9): computed as 1 and stored. Thenheight(20): computesheight(15)= 1 andheight(7)= 1, stores both, then stores 20 as 2. Cache: {9: 1, 15: 1, 7: 1, 20: 2}. Difference 1, passes.check(9): children are null, heights 0 and 0. Passes.check(20):height(15)andheight(7)are cache hits, both 1. Passes.check(15)andcheck(7): pass.
The answer is true, and each real node height was computed exactly once.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of nodes. Each node's height is computed once, then every later request is an O(1) lookup, so all height work totals O(n). check visits each node once and does a constant number of lookups, which adds another O(n). The map holds one entry per node, so space is O(n). The call stack adds O(h), which never exceeds O(n).
PythonTested in our runner
from typing import List, Optional
import sys
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
sys.setrecursionlimit(20000)
memo = {}
def height(node):
if not node:
return 0
if node in memo:
return memo[node]
memo[node] = 1 + max(height(node.left), height(node.right))
return memo[node]
def check(node):
if not node:
return True
if abs(height(node.left) - height(node.right)) > 1:
return False
return check(node.left) and check(node.right)
return check(root)JavaTested in our runner
import java.util.*;
class Solution {
public boolean isBalanced(TreeNode root) {
return check(root, new HashMap<>());
}
private boolean check(TreeNode node, Map<TreeNode, Integer> memo) {
if (node == null) return true;
if (Math.abs(height(node.left, memo) - height(node.right, memo)) > 1) return false;
return check(node.left, memo) && check(node.right, memo);
}
private int height(TreeNode node, Map<TreeNode, Integer> memo) {
if (node == null) return 0;
Integer cached = memo.get(node);
if (cached != null) return cached;
int h = 1 + Math.max(height(node.left, memo), height(node.right, memo));
memo.put(node, h);
return h;
}
};C++Tested in our runner
#include <algorithm>
#include <cstdlib>
#include <unordered_map>
class Solution {
public:
bool isBalanced(TreeNode* root) {
std::unordered_map<TreeNode*, int> memo;
return check(root, memo);
}
private:
int height(TreeNode* node, std::unordered_map<TreeNode*, int>& memo) {
if (node == nullptr) return 0;
auto it = memo.find(node);
if (it != memo.end()) return it->second;
int h = 1 + std::max(height(node->left, memo), height(node->right, memo));
memo[node] = h;
return h;
}
bool check(TreeNode* node, std::unordered_map<TreeNode*, int>& memo) {
if (node == nullptr) return true;
if (std::abs(height(node->left, memo) - height(node->right, memo)) > 1) return false;
return check(node->left, memo) && check(node->right, memo);
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
const memo = new Map();
const height = (node) => {
if (node === null) return 0;
if (memo.has(node)) return memo.get(node);
const h = 1 + Math.max(height(node.left), height(node.right));
memo.set(node, h);
return h;
};
const check = (node) => {
if (node === null) return true;
if (Math.abs(height(node.left) - height(node.right)) > 1) return false;
return check(node.left) && check(node.right);
};
return check(root);
};GoTested in our runner
func memoHeight(node *TreeNode, memo map[*TreeNode]int) int {
if node == nil {
return 0
}
if h, ok := memo[node]; ok {
return h
}
l, r := memoHeight(node.Left, memo), memoHeight(node.Right, memo)
h := r + 1
if l > r {
h = l + 1
}
memo[node] = h
return h
}
func memoCheck(node *TreeNode, memo map[*TreeNode]int) bool {
if node == nil {
return true
}
diff := memoHeight(node.Left, memo) - memoHeight(node.Right, memo)
if diff > 1 || diff < -1 {
return false
}
return memoCheck(node.Left, memo) && memoCheck(node.Right, memo)
}
func isBalanced(root *TreeNode) bool {
return memoCheck(root, make(map[*TreeNode]int))
}C#Tested in our runner
public class Solution {
public bool isBalanced(TreeNode root) {
return Check(root, new Dictionary<TreeNode, int>());
}
private bool Check(TreeNode node, Dictionary<TreeNode, int> memo) {
if (node == null) return true;
if (Math.Abs(Height(node.left, memo) - Height(node.right, memo)) > 1) return false;
return Check(node.left, memo) && Check(node.right, memo);
}
private int Height(TreeNode node, Dictionary<TreeNode, int> memo) {
if (node == null) return 0;
if (memo.TryGetValue(node, out int cached)) return cached;
int h = 1 + Math.Max(Height(node.left, memo), Height(node.right, memo));
memo[node] = h;
return h;
}
}
Solution pattern
Recursive Postorder Traversal
Approach 3: Bottom-up DFS with a -1 sentinelOptimalRecursive Postorder Traversal
What's slow: the memoized version fixes the repeated work but still runs two passes of logic (heights and checks) and spends O(n) on a map. It also keeps descending into children after a violation is already known.
The insight that fixes it: do the balance check inside the height calculation, in postorder. Each call returns the subtree height if the subtree is balanced and -1 if it is not. The parent reads both children's results, and the checking and measuring happen in the same visit. No map is needed, because each height is used once, right when its parent needs it.
Steps
- Write
dfs(node)returning an int: the height, or -1 for an unbalanced subtree. - If
nodeis null, return 0. - Set
left = dfs(node.left). If it is -1, return -1 immediately. - Set
right = dfs(node.right). If it is -1, return -1 immediately. - If
abs(left - right) > 1, return -1. - Otherwise return
max(left, right) + 1. - In
isBalanced, returndfs(root) != -1.
Dry run
Trace on [3,9,20,null,null,15,7]. Every null child returns 0.
| Step | Node finished | left | right | abs diff | Returns |
|---|---|---|---|---|---|
| 1 | 9 | 0 | 0 | 0 | 1 |
| 2 | 15 | 0 | 0 | 0 | 1 |
| 3 | 7 | 0 | 0 | 0 | 1 |
| 4 | 20 | 1 (from 15) | 1 (from 7) | 0 | 2 |
| 5 | 3 | 1 (from 9) | 2 (from 20) | 1 | 3 |
The root call returned 3, which is not -1, so the answer is true.
For contrast, take [1,2,null,3] where 3 hangs under 2 on the left. Node 3 returns 1, node 2 returns 2, and node 1 sees left 2 and right 0. The difference is 2, so node 1 returns -1 and the answer is false.
Complexity
| Time | O(n) |
|---|---|
| Space | O(h) |
Let n be the number of nodes and h the tree height. Each node is visited exactly once, and each visit does constant work: two comparisons and one max. That gives O(n) time, and early exits only make it faster. The only extra memory is the recursion stack, whose depth equals the longest root-to-leaf path, so space is O(h). That is O(log n) for a balanced tree and O(n) for a chain.
PythonTested in our runner
from typing import List, Optional
import sys
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
sys.setrecursionlimit(20000)
def dfs(node):
# Returns the height if balanced, else -1
if not node:
return 0
left = dfs(node.left)
if left == -1:
return -1
right = dfs(node.right)
if right == -1:
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1
return dfs(root) != -1JavaTested in our runner
import java.util.*;
class Solution {
public boolean isBalanced(TreeNode root) {
return dfs(root) != -1;
}
// Returns the height if balanced, else -1
private int dfs(TreeNode node) {
if (node == null) return 0;
int left = dfs(node.left);
if (left == -1) return -1;
int right = dfs(node.right);
if (right == -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
}
}C++Tested in our runner
#include <algorithm>
#include <cstdlib>
class Solution {
public:
bool isBalanced(TreeNode* root) {
return dfs(root) != -1;
}
private:
// Returns the height if balanced, else -1
int dfs(TreeNode* node) {
if (node == nullptr) return 0;
int left = dfs(node->left);
if (left == -1) return -1;
int right = dfs(node->right);
if (right == -1) return -1;
if (std::abs(left - right) > 1) return -1;
return std::max(left, right) + 1;
}
};JavaScriptTested in our runner
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
// Returns the height if balanced, else -1
const dfs = (node) => {
if (node === null) return 0;
const left = dfs(node.left);
if (left === -1) return -1;
const right = dfs(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return Math.max(left, right) + 1;
};
return dfs(root) !== -1;
};GoTested in our runner
// Returns the height if balanced, else -1
func balancedHeight(node *TreeNode) int {
if node == nil {
return 0
}
left := balancedHeight(node.Left)
if left == -1 {
return -1
}
right := balancedHeight(node.Right)
if right == -1 {
return -1
}
diff := left - right
if diff > 1 || diff < -1 {
return -1
}
if left > right {
return left + 1
}
return right + 1
}
func isBalanced(root *TreeNode) bool {
return balancedHeight(root) != -1
}C#Tested in our runner
public class Solution {
public bool isBalanced(TreeNode root) {
return Dfs(root) != -1;
}
// Returns the height if balanced, else -1
private int Dfs(TreeNode node) {
if (node == null) return 0;
int left = Dfs(node.left);
if (left == -1) return -1;
int right = Dfs(node.right);
if (right == -1) return -1;
if (Math.Abs(left - right) > 1) return -1;
return Math.Max(left, right) + 1;
}
}Common mistakes
- Checking only the root with
abs(height(root.left) - height(root.right)) <= 1. The rule applies to every node, so a tree can pass at the root and fail deep inside. Run the check at every node, or propagate -1 from below. - Not propagating the sentinel, for example computing
max(left, right) + 1whenleft == -1. A -1 next to a height of 0 has difference 1, so the parent wrongly looks balanced. Return -1 immediately when either child returns it. - Calling
heightat every node in the top-down version and thinking it is O(n). Each call walks a whole subtree, so a chain costs O(n^2). Cache heights or switch to the bottom-up return value. - Mixing height conventions, such as returning 1 for null and 1 for a leaf. Pick one: null is 0 and a leaf is 1. Using the wrong base case can flip a difference from 1 to 0 and hide violations.
- Returning a boolean from the recursive helper and losing the height. The parent needs the height to compare. Return an int with -1 as the failure value, or return a pair.
- Relying on Python's default recursion limit. A chain of 5000 nodes exceeds 1000 frames and raises
RecursionError. Raise the limit withsys.setrecursionlimitor use an explicit stack.
Edge cases
- Empty tree,
root = []: return true, because a null node has height 0 and nothing to violate. - Single node: return true. Both children are null with height 0, difference 0.
- Left-leaning chain of 3 nodes (
[1,2,null,3]): return false. The root sees heights 2 and 0. - Chain of exactly 2 nodes (
[1,2]): return true. Heights 1 and 0 differ by exactly 1, which is allowed. - Root balanced but a deep subtree not (for example
[1,2,2,3,3,null,null,4,4]): return false. The failure sits at node 2, not at the root. - Chain of 5000 nodes: return false in O(n), and make sure the recursion depth of 5000 does not overflow in your language.
Follow-ups interviewers ask
- Can you do it iteratively, without recursion?
- Yes. Run an iterative postorder traversal with an explicit stack, and store each finished node's height in a map. When you pop a node, read its children's heights from the map and compare them. Stop with false on a violation. It keeps O(n) time and avoids stack overflow on a 5000-node chain, at the cost of O(n) map space.
- What if you must return the first unbalanced node instead of a boolean?
- Keep the postorder shape but return the height through a second channel, such as a pair of height and offending node. The first node whose children differ by more than 1 is recorded, then passed up unchanged. The cost stays O(n) time and O(h) stack.
- How is this related to rebuilding a balanced tree, as in LeetCode 1382?
- That problem is the reverse direction. You take an unbalanced binary search tree and do an inorder traversal to get a sorted array. Then you build a tree by picking the middle element as root recursively. The result has height about log n, so this page's check would return true on it.
Balanced Binary Tree FAQ
What is the time complexity of Balanced Binary Tree?
The bottom-up solution runs in O(n), where n is the number of nodes, because each node is visited once with constant work. The top-down brute force that recomputes height at every node is O(n^2) on a chain. Space is O(h) for the recursion stack.
Why use postorder DFS for Balanced Binary Tree?
A node's balance depends on both children's heights, so the children must finish first. Postorder visits left, right, then the node, which hands the parent exactly the information it needs. It also lets you return -1 and stop checking as soon as one node fails.
What is a height-balanced tree and how is its height defined?
A tree is height-balanced when every node has left and right subtree heights that differ by at most 1. Height here counts nodes on the longest downward path, with an empty tree at 0 and a leaf at 1. Counting edges instead shifts every value by one but gives the same differences.
Can Balanced Binary Tree be solved in O(1) extra space?
Not with the usual approach, which needs an O(h) stack for the recursion. Reaching O(1) would need a Morris-style traversal that temporarily rewires pointers, and you would still need somewhere to keep child heights. For an interview, O(h) space is the accepted answer.
Does a binary search tree have to be balanced?
No. A binary search tree only needs the ordering rule, where left values are smaller and right values are larger. Inserting sorted data into a plain BST produces a chain. Self-balancing variants such as AVL trees enforce the same height difference rule used on this page.
Is there a Python-specific problem with Balanced Binary Tree?
Yes, the recursion limit. Python defaults to about 1000 frames, and a chain of 5000 nodes needs about 5000. Calling sys.setrecursionlimit with a larger value, or writing an iterative postorder, avoids the RecursionError.
Asked at
See which companies ask this — Pro
Related problems
- Diameter of Binary Tree · same technique: Recursive Postorder Traversal
- Maximum Depth of Binary Tree · same technique: Recursive Postorder Traversal
- Binary Tree Postorder Traversal · same technique: Recursive Postorder Traversal
- House Robber III · same technique: Recursive Postorder Traversal
- Delete Leaves With a Given Value · same technique: Recursive Postorder Traversal
- Same Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Invert Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Subtree of Another Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Binary Tree Preorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)