Skip to contentKEEP THE CRAFTTHE SANCTUARY

Balanced Tree

Balancing protects BST height while preserving inorder key order. First measure child heights consistently, then understand why rotations move the median of three distinct keys to the local root; the fixed three-key Lab is not a complete AVL implementation.

1 practice exercise4 interview problems

Recognize it when Ordered updates need a height guarantee rather than an accidental good insertion order.

Checking your account…

Balanced Tree Code Labs

Balance Protects Height

A binary-search tree gets its speed from height, not from the word “tree.” Sorted insertion can produce a chain, turning search and update into O(n). A balanced tree preserves BST ordering while bounding the height, so those operations remain O(log n) in the worst case.

Measure Balance Factors

For an AVL-style model, define a node’s balance factor as height(left) - height(right). Values from -1 through 1 are locally balanced. Store or recompute height consistently: an empty child has height 0, and a node has one plus the larger child height.

Measure Balance Factors

Reference
def balance_factors(tree):
    heights = [0] * len(tree)
    factors = {}
    for index in range(len(tree) - 1, -1, -1):
        if tree[index] is None:
            continue
        left = 2 * index + 1
        right = left + 1
        left_height = heights[left] if left < len(tree) else 0
        right_height = heights[right] if right < len(tree) else 0
        heights[index] = 1 + max(left_height, right_height)
        factors[tree[index]] = left_height - right_height
    return [factors[value] for value in tree if value is not None]
Practice

Implement balance_factors(tree). tree is a level-order list whose values are keys and whose null children are None. Return the balance factor height(left) - height(right) for each non-None key in level-order. Use a valid complete-index tree with unique hashable keys and no non-None nodes below a missing parent.

Public tests

  • Measure local height differences

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Measure Balance Factors

def balance_factors(tree):
    heights = [0] * len(tree)
    factors = {}
    for index in range(len(tree) - 1, -1, -1):
        if tree[index] is None:
            continue
        left = 2 * index + 1
        right = left + 1
        left_height = heights[left] if left < len(tree) else 0
        right_height = heights[right] if right < len(tree) else 0
        heights[index] = 1 + max(left_height, right_height)
        factors[tree[index]] = left_height - right_height
    return [factors[value] for value in tree if value is not None]

Trace Child Heights Before Parent Balance

Run the existing factor Lab on [8, 4, 12, 2, None]. Reverse index order makes every child height available before the parent. Returned factors then follow the original level-order key sequence rather than the reverse calculation order.

print(balance_factors([8, 4, 12, 2, None])) followed by print(balance_factors([]))

Step Executed statement State Why
1 heights = [0] * len(tree); factors = {} heights = [0, 0, 0, 0, 0]; factors = {} Absent and out-of-range children contribute zero height.
2 if tree[index] is None: continue index = 4 skipped; heights remain zero A missing slot supplies no node and no factor.
3 heights[index] = 1 + max(left_height, right_height); factors[tree[index]] = left_height - right_height indices 3 and 2: heights = [0, 0, 1, 1, 0]; factors[2] = factors[12] = 0 Both leaves have two zero child heights.
4 heights[index] = 1 + max(left_height, right_height); factors[tree[index]] = left_height - right_height index = 1; left_height = 1; right_height = 0; heights[1] = 2; factors[4] = 1 Child indices exceed parent indices, so their values are ready.
5 heights[index] = 1 + max(left_height, right_height); factors[tree[index]] = left_height - right_height index = 0; child heights = 2, 1; heights[0] = 3; factors[8] = 1 The parent adds one level but subtracts child heights for balance.
6 return [factors[value] for value in tree if value is not None] result = [1, 1, 0, 0] The final pass restores the authored level-order result order.
Print Output
1 [1, 1, 0, 0]
2 []

The root factor is one because its left height is two and its right height is one. General balance must hold at every node, not just at the root. This Lab requires unique hashable keys because its factor dictionary associates each key with one result.

Repair with Rotations

A rotation changes local parent-child links without changing inorder key order. Outer shapes need one rotation; inner left-right and right-left shapes need two. For three distinct keys, the median becomes root and the extrema become its children.

Recognize Three-Node Tree Rotations

Reference
def balance_three_nodes(insertion_order):
    left, root, right = sorted(insertion_order)
    return [root, left, right]
Practice

Implement balance_three_nodes(insertion_order). insertion_order contains exactly three distinct comparable values. Return [root, left_child, right_child] for the balanced BST after the required single or double rotation.

Public tests

  • Verify all three-node insertion shapes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Recognize Three-Node Tree Rotations

def balance_three_nodes(insertion_order):
    left, root, right = sorted(insertion_order)
    return [root, left, right]

Choose a Balanced Tree or Sorted Array

Choose a balanced tree when ordered keys change frequently and you need worst-case logarithmic search, insertion, or deletion. Choose a sorted array when reads dominate: binary search is simple and cache-friendly, but middle insertion costs O(n). In Python interviews, bisect over a list is often the clearer choice unless dynamic ordered updates are central.

Explain It in an Interview

Say: “BST order makes inorder traversal sorted; the balance invariant protects logarithmic height. After an update, I repair the first unbalanced ancestor with rotations that preserve inorder order.” Then name the rotation case and derive O(log n) from the bounded height. The two Labs isolate measurement and a three-key result; a full AVL update must also reconnect the rotated subtree and refresh affected heights. Insertion may finish height repair after the first corrected ancestor, while deletion can require repairs farther toward the root.

Sorted List to Balanced BST(opens in a new tab) tests the same height goal when the input is already ordered. The Python bisect reference(opens in a new tab) is the useful comparison point for an array-backed alternative.

Python Version Note

Python 3.11+

The examples use standard Python containers and syntax available in the supported browser runtime; Balanced Tree itself is taught as an interview abstraction.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Measure factors over m array slotsO(m)O(m)Reverse scan includes None slots; heights, factor dictionary and returned factors use linear space under ordinary hashing.
Normalize exactly three keysO(1)O(1)Input size is fixed at three, and comparison cost is bounded; this does not describe general AVL maintenance.
Search/update in a maintained balanced BSTO(log(n + 1))O(log(n + 1))n keys; full balancing invariant and correct update repairs are supplied by the implementation, not by this three-key Lab.

Space

O(m) for measure factors over m array slots; O(1) for normalize exactly three keys; O(n) for search/update in a maintained balanced bst.

Assumptions

  • Reverse scan includes None slots; heights, factor dictionary and returned factors use linear space under ordinary hashing.
  • Input size is fixed at three, and comparison cost is bounded; this does not describe general AVL maintenance.
  • n keys; full balancing invariant and correct update repairs are supplied by the implementation, not by this three-key Lab.

Invariants Worth Saying Aloud

  1. Height is one plus the maximum child height; empty children have height zero.
  2. AVL-style balance requires every node's child-height difference to stay between -1 and 1.
  3. Rotations preserve inorder key order and must reconnect the resulting subtree root.

When To Use Or Avoid Balanced Tree

Use It When

  • Measure heights bottom-up before selecting an AVL-style rotation case.
  • Use a maintained balanced structure when dynamic ordered operations are the actual contract.

Choose Another Tool When

  • Use a sorted array and bisect when reads dominate and linear insertion is acceptable.
  • Do not generalize a three-key normalization into a full insertion/deletion implementation.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Adding branch heights rather than choosing a path

A node's height follows its longest child path. Summing branch heights exaggerates height and can trigger wrong repairs.

Prevent it: Use one plus the maximum child height.

Avoid

height = 1 + left_height + right_height

Use instead

height = 1 + max(left_height, right_height)

Assuming the second insertion is always the balanced root

An inner right-left shape can place the median third in input order. The local root follows sorted order, not insertion position.

Prevent it: Identify the median among the three distinct keys.

Avoid

root = insertion_order[1]

Use instead

root = sorted(insertion_order)[1]

Checking only the root's balance factor

A root can be balanced while a lower subtree violates the AVL limit.

Prevent it: Require the balance condition at every node.

Avoid

balanced = abs(factors[0]) <= 1

Use instead

balanced = all(abs(factor) <= 1 for factor in factors)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.