Height-Balanced Nodes in Heap-Array Trees
Trees & GraphsModel answerLast updated
Traverse a binary tree stored in heap-index layout to find every node whose subtree is height-balanced, returning each with its tree level.
Balanced Subtrees in an Array-Backed Binary Tree
A binary tree is stored as a zero-indexed array nodes using the standard heap layout:
- Index
0holds the root. - A node at index
ihas its left child at2*i + 1and its right child at2*i + 2. - A
Noneentry means no node exists at that position. Any index>= len(nodes)is also treated as empty. - A node is only considered part of the tree if every ancestor up to the root is non-
None. A non-Noneentry whose parent isNoneis ignored.
Height definition:
- An empty subtree has height
0. - A non-empty subtree has height
1 + max(left_height, right_height).
Height-balanced subtree: A subtree rooted at node u is height-balanced if:
- Its left subtree is height-balanced (empty counts as balanced).
- Its right subtree is height-balanced.
- The absolute difference between left and right subtree heights is at most
1.
Your task: implement balanced_nodes(nodes) that returns all present nodes whose subtree is height-balanced. For each, report (index, level), where level is 0-indexed from the root. Sort results by level ascending, then by index ascending.
def balanced_nodes(nodes: list[int | None]) -> list[tuple[int, int]]:
pass
Constraints
0 <= len(nodes) <= 10^5nodes[i]is an integer in[-10^9, 10^9]orNone.
Examples
Example 1
Input: nodes = [1, 2, None, 3]
Output: [(1, 1), (3, 2)]
Node 0 has a left subtree of height 2 and a right subtree of height 0; difference is 2, so it is not balanced.
Node 1 has heights 1 (left) and 0 (right); difference is 1, both children balanced — node 1 is balanced at level 1.
Node 3 is a leaf — trivially balanced at level 2.
Example 2
Input: nodes = [1, 2, 3, 4, None, 6, 7]
Output: [(0, 0), (1, 1), (2, 1), (3, 2), (5, 2), (6, 2)]
Every node in this tree is balanced. The root's left subtree (height 2) and right subtree (height 2) differ by 0.
Example 3
Input: nodes = []
Output: []
Hints
Hint 1
Height and balance together require information from children before a parent can be evaluated — think about what traversal order naturally satisfies that, and whether the heap index layout already encodes it without any explicit recursion.
Hint 2
A node's level in a heap-indexed tree can be read directly from its index: level = (i + 1).bit_length() - 1. Sketch out a few indices to convince yourself, then think about whether collecting results in ascending index order already gives you the required sort for free.
Hint 3
Watch out for 'orphaned' entries: a non-None value at index i is irrelevant if any ancestor is None. A single forward pass over indices 0..n-1 can mark which nodes are truly present before you compute anything else.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is computing, for each node, two things: the height of its subtree and whether that subtree is balanced. Both depend on the same information from both children, so this is a bottom-up (post-order) computation.
The heap layout makes this unusually convenient: a child's index is always strictly greater than its parent's index (2i+1 > i). That means scanning indices from len(nodes)-1 down to 0 visits every child before its parent — a valid post-order evaluation with no recursion or explicit stack required.
Two-pass algorithm
Pass 1 — reachability (forward, O(n)).
A node at index i is present only when nodes[i] is not None and its parent is also present. Since parents have smaller indices, a single forward scan suffices:
present[0] = nodes[0] is not None
for i in range(1, n):
present[i] = nodes[i] is not None and present[(i - 1) // 2]
This correctly handles "orphaned" entries: a non-None value whose ancestor chain contains a None is not a real tree node.
Pass 2 — height and balance (backward, O(n)).
For each present node, look up the precomputed results for its children. Out-of-range or absent children default to height 0 and balanced = True, matching the problem's definition of an empty subtree.
for i in range(n - 1, -1, -1):
if not present[i]:
continue
l, r = 2*i + 1, 2*i + 2
hl = height[l] if l < n else 0
hr = height[r] if r < n else 0
bl = balanced[l] if l < n else True
br = balanced[r] if r < n else True
height[i] = 1 + max(hl, hr)
balanced[i] = bl and br and abs(hl - hr) <= 1
Output — already sorted.
The level of index i is (i + 1).bit_length() - 1. Level 0 is just index 0; level 1 is indices 1–2; level 2 is indices 3–6; and so on. Level never decreases as i increases, so iterating over indices 0..n-1 and collecting balanced nodes produces results already sorted by (level, index). No sort step needed.
Complete solution
def balanced_nodes(nodes: list[int | None]) -> list[tuple[int, int]]:
n = len(nodes)
if n == 0 or nodes[0] is None:
return []
# Pass 1: mark which indices represent actual tree nodes.
present = [False] * n
present[0] = True
for i in range(1, n):
present[i] = nodes[i] is not None and present[(i - 1) // 2]
# Pass 2: reverse scan — children are always processed before parents.
height = [0] * n # absent nodes default to height 0
balanced = [True] * n # absent nodes default to balanced
for i in range(n - 1, -1, -1):
if not present[i]:
continue
l, r = 2 * i + 1, 2 * i + 2
hl = height[l] if l < n else 0
hr = height[r] if r < n else 0
bl = balanced[l] if l < n else True
br = balanced[r] if r < n else True
height[i] = 1 + max(hl, hr)
balanced[i] = bl and br and abs(hl - hr) <= 1
# Level is monotone in index, so index order == (level, index) order.
return [
(i, (i + 1).bit_length() - 1)
for i in range(n)
if present[i] and balanced[i]
]
Walkthrough: [1, 2, None, 3]
| Index | Present | Height | Balanced | Level |
|---|---|---|---|---|
| 3 | yes | 1 | yes (leaf) | 2 |
| 2 | no | 0 | yes (default) | — |
| 1 | yes | 2 | yes (` | 1-0 |
| 0 | yes | 3 | no (` | 2-0 |
Output: [(1, 1), (3, 2)] ✓
Complexity
- Time: O(n) — two linear passes, constant work per index.
- Space: O(n) — three auxiliary arrays plus the output list.
A naive recursive approach that recomputes height independently from balance checking is O(n²) on a degenerate chain-shaped tree (each level's height triggers a full re-traversal). Combining height and balance in a single upward pass avoids that.
Edge cases to mention
- Empty array or
Noneroot: return[]immediately. - Single node: always balanced; output
[(0, 0)]. - Orphaned entries (e.g.
[1, None, 2, 5]): index3is a child of index1which is absent, so index3is not in the tree. Pass 1 handles this correctly. - Node values don't affect the answer — only presence (
Nonevs. non-None) matters. Negative integers and zero require no special handling. - Level formula:
(i + 1).bit_length() - 1works because adding 1 shifts indexiinto the range[2^L, 2^(L+1) - 1]for levelL, and every integer in that range has bit length exactlyL + 1.
Common mistakes
- Using
i.bit_length() - 1for level — this gives-1for the root and is off by one everywhere. - Forgetting orphaned entries and treating any non-
Nonevalue as a real node. - Treating absent children as having
balanced = Falserather thanTrue, which incorrectly marks leaves as unbalanced. - Separating height and balance into two passes or two recursive functions, leading to redundant traversals and O(n²) behaviour on skewed trees.