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)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…
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.
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.
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]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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
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]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. |
| 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.
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.
def balance_three_nodes(insertion_order):
left, root, right = sorted(insertion_order)
return [root, left, right]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.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def balance_three_nodes(insertion_order):
left, root, right = sorted(insertion_order)
return [root, left, right]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.
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 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)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Measure factors over m array slots | O(m) | O(m) | Reverse scan includes None slots; heights, factor dictionary and returned factors use linear space under ordinary hashing. |
| Normalize exactly three keys | O(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 BST | O(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. |
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.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
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.
height = 1 + left_height + right_heightheight = 1 + max(left_height, right_height)Where you will hit this: Recognize Three-Node Tree Rotations(opens in a new tab)
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.
root = insertion_order[1]root = sorted(insertion_order)[1]Where you will hit this: Recognize Three-Node Tree Rotations(opens in a new tab)
A root can be balanced while a lower subtree violates the AVL limit.
Prevent it: Require the balance condition at every node.
balanced = abs(factors[0]) <= 1balanced = all(abs(factor) <= 1 for factor in factors)Where you will hit this: Sorted List to Balanced BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27