15% off all plans & roadmaps Use code

See plans

Balanced Binary Tree

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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Write height(node): return 0 for null, else 1 + max(height(left), height(right)).
  2. Write check(node): return true for null.
  3. At each node, compute height(node.left) and height(node.right).
  4. If their absolute difference is greater than 1, return false.
  5. Otherwise return check(node.left) and check(node.right).
  6. 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) and check(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

TimeO(n^2)
SpaceO(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)

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

  1. Create an empty map from node to height.
  2. Write height(node): return 0 for null, return the stored value if present.
  3. Otherwise compute 1 + max(height(left), height(right)), store it, and return it.
  4. Write check(node) as in the brute force: null is balanced.
  5. Compare the cached heights of both children and return false if they differ by more than 1.
  6. 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 for height(9): computed as 1 and stored. Then height(20): computes height(15) = 1 and height(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) and height(7) are cache hits, both 1. Passes.
  • check(15) and check(7): pass.

The answer is true, and each real node height was computed exactly once.

Complexity

TimeO(n)
SpaceO(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)
Recursive Postorder Traversal pattern infographic for Balanced Binary Tree

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

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

  1. Write dfs(node) returning an int: the height, or -1 for an unbalanced subtree.
  2. If node is null, return 0.
  3. Set left = dfs(node.left). If it is -1, return -1 immediately.
  4. Set right = dfs(node.right). If it is -1, return -1 immediately.
  5. If abs(left - right) > 1, return -1.
  6. Otherwise return max(left, right) + 1.
  7. In isBalanced, return dfs(root) != -1.

Dry run

Trace on [3,9,20,null,null,15,7]. Every null child returns 0.

StepNode finishedleftrightabs diffReturns
190001
2150001
370001
4201 (from 15)1 (from 7)02
531 (from 9)2 (from 20)13

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

TimeO(n)
SpaceO(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) != -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) + 1 when left == -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 height at 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 with sys.setrecursionlimit or 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

Practise it