← Whiteboard questions

Balanced Binary Tree

Check that no node has one side much taller than the other

DSA, Easy, Trees

Which structure or algorithm, and what does it cost.

You get a binary tree tree. Your code may take the root node or the list. Each node has val, left and right, null when missing. Either is fine; no conversion is needed. The examples use a level-order list. It holds values row by row, left to right. Null marks a missing child. A missing node has no entries below it. An empty list is an empty tree. The height of a node is the number of nodes on its longest path down. A tree is balanced when, at every node, the heights of its left and right subtrees differ by at most 1. Return true if the tree is balanced.

Examples

Input tree = [7, 3, 9, 1, null, null, 4]
Output true
Why every node has side heights that differ by 0 or 1.
Input tree = [1, 2, 2, 3, null, null, 3, 4, null, null, 4]
Output false
Why the root looks fine, with both sides of height 3. The left node 2 has a left height of 2 and a right height of 0.
Input tree = []
Output true
Why an empty tree has no node that can break the rule.

Constraints

Your answer must contain

Target Aim for O(n) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

The rule applies to every node, not only to the root. What would you check at one node?

Hint 2 the approach

At one node you need the height of each side. Think about when a node already knows those heights, and who computes them.

Hint 3 the key step

Compute heights from the leaves upward. At each node compare its two child heights. If they differ by more than 1, answer false at once.

Walkthrough

Full walkthrough brute force to best

Brute force

At every node, measure the height of its left side and its right side by walking down each one, then compare. Each walk covers a whole subtree, so the same nodes are measured again at every level above them. Even when the check stops at the first failure, a balanced tree measures all its nodes once per level, which is O(n log n) time.

Best method

Measure each height once, from the leaves upward, and check the rule on the way. A node can only be checked when its two child heights are known, so process children before parents: go through the nodes in reverse reading order. At each node, compare the two child heights. If they differ by more than 1, return false. Otherwise the node is 1 taller than its taller child. If no node fails, the tree is balanced. Each node is handled once, so the work is linear. Checking the root alone is not enough, because a node deep inside can break the rule while the root looks fine.

Hand trace

Run on [1, 2, 2, 3, null, null, 3, 4, null, null, 4]. Reading order is 1, 2, 2, 3, 3, 4, 4, so we go from the last: 4, 4, 3, 3, 2, 2, 1. The two bottom nodes 4 are leaves: heights 1 and 1, no problem. The right node 3 has left height 0 and right height 1, so its height is 2. The left node 3 has left height 1 and right height 0, so its height is 2. The right node 2 has left height 0 and right height 2. That differs by 2, so we return false before we reach the root.

Code

def is_balanced(root):
    order = [root] if root else []
    for node in order:
        order.extend(child for child in (node.left, node.right) if child)
    height = {}
    for node in reversed(order):
        left, right = height.get(node.left, 0), height.get(node.right, 0)
        if abs(left - right) > 1:
            return False
        height[node] = 1 + max(left, right)
    return True

Time and memory

O(n) time, because each node is listed once and checked once. O(n) memory for the order and the heights.

Common mistakes

  • Comparing only the two sides of the root. A deep node can be unbalanced while the root looks fine, as in example 2.
  • Allowing a difference of 0 only. A difference of 1 is allowed.
  • Measuring the heights again at every node. This repeats work and costs O(n log n) even on a balanced tree.

Related problems

More Trees problems
Balanced Binary Tree: hints, walkthrough and Python solution