Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Binary Tree itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)A binary-tree node has at most two children, and each child supplies an independent subtree result. Define absence and height units first, then combine count, height and leaves after child returns or use a queue when results belong to levels.
3 practice exercises16 interview problems
Recognize it when Every node has distinct left/right child positions.
Checking your account…
A binary-tree node has at most left and right children. Each child begins an independent
subproblem, so a recursive function should define exactly what it returns for one subtree. The empty
child is a real base case, not an exception to patch after the recursion.
Choose whether height counts nodes or edges and state the empty-tree value before coding. With
node-count height, an empty subtree has height zero and a leaf has height one. A complete-index array
is useful for Labs, but None under an unreachable parent does not create a floating node.
Postorder recursion receives completed left and right results before computing the current node.
Count is 1 + left_count + right_count; height is 1 + max(left_height, right_height); a leaf has
no reachable children. The same pattern powers balance, diameter, and subtree aggregation.
def binary_tree_profile(level_order):
def visit(index):
if index >= len(level_order) or level_order[index] is None:
return 0, 0, 0
left = visit(2 * index + 1)
right = visit(2 * index + 2)
count = 1 + left[0] + right[0]
height = 1 + max(left[1], right[1])
leaves = 1 if left[0] == right[0] == 0 else left[2] + right[2]
return count, height, leaves
return list(visit(0))Implement binary_tree_profile(level_order). Count reachable nodes, node-count height, and leaves in a complete-index array with None gaps.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def binary_tree_profile(level_order):
def visit(index):
if index >= len(level_order) or level_order[index] is None:
return 0, 0, 0
left = visit(2 * index + 1)
right = visit(2 * index + 2)
count = 1 + left[0] + right[0]
height = 1 + max(left[1], right[1])
leaves = 1 if left[0] == right[0] == 0 else left[2] + right[2]
return count, height, leaves
return list(visit(0))Use the actual profile Lab with [0, None, 2, 9]. The zero root is present. Entry 9 lies below missing index 1, so it is never visited; only the root and its right leaf contribute.
print(binary_tree_profile([0, None, 2, 9])) followed by print(binary_tree_profile([None, 9]))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | left = visit(2 * index + 1) |
root index = 0; visit(1) returns (0, 0, 0) |
None ends the entire left subtree, including stored index 3. |
| 2 | left = visit(2 * index + 1); right = visit(2 * index + 2) |
at index 2: visit(5) and visit(6) return (0, 0, 0) |
Out-of-range children are explicit empty subtrees. |
| 3 | count = 1 + left[0] + right[0]; height = 1 + max(left[1], right[1]); leaves = 1 if left[0] == right[0] == 0 else left[2] + right[2] |
index 2: count = 1; height = 1; leaves = 1 |
Both children are empty, so the right node is a leaf. |
| 4 | count = 1 + left[0] + right[0]; height = 1 + max(left[1], right[1]) |
root: left = (0, 0, 0); right = (1, 1, 1); count = 2; height = 2 |
The completed right result adds one node and one height level. |
| 5 | leaves = 1 if left[0] == right[0] == 0 else left[2] + right[2]; return list(visit(0)) |
root leaves = 1; result = [2, 2, 1] |
The root has a reachable child, so it sums child leaves instead of counting itself. |
| Output | |
|---|---|
| 1 | [2, 2, 1] |
| 2 | [0, 0, 0] |
The three return fields answer different questions. Count adds child counts, height takes the larger child height, and leaf count identifies nodes without reachable children. A missing root makes every stored descendant irrelevant.
A queue groups nodes by distance from the root. Capture the current queue size, remove exactly that many nodes, and enqueue their reachable children for the next level. This differs from DFS because the frontier owns a whole breadth boundary.
from collections import deque
def binary_tree_levels(level_order):
if not level_order or level_order[0] is None:
return []
queue = deque([0])
levels = []
while queue:
level = []
for _ in range(len(queue)):
index = queue.popleft()
level.append(level_order[index])
for child in (2 * index + 1, 2 * index + 2):
if child < len(level_order) and level_order[child] is not None:
queue.append(child)
levels.append(level)
return levelsImplement binary_tree_levels(level_order). Return reachable values grouped by depth, ignoring entries below missing parents.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
from collections import deque
def binary_tree_levels(level_order):
if not level_order or level_order[0] is None:
return []
queue = deque([0])
levels = []
while queue:
level = []
for _ in range(len(queue)):
index = queue.popleft()
level.append(level_order[index])
for child in (2 * index + 1, 2 * index + 2):
if child < len(level_order) and level_order[child] is not None:
queue.append(child)
levels.append(level)
return levelsUse recursion when the return value naturally summarizes a subtree and height is safe for Python’s call stack. Use an explicit stack for deep trees or controlled preorder/inorder traversal, and a queue for level order or minimum-edge distance. The Python recursion reference(opens in a new tab) does not guarantee tail-call elimination.
None array entry as reachable accepts children of missing parents.Say what the helper returns for one subtree and verify the empty node first. Then show how left and right results combine without revisiting nodes. State O(n) time because each reachable node is processed once; auxiliary space is O(h) recursion or O(w) queue width, depending on traversal.
Profile a Binary Tree(opens in a new tab) practices aggregation. Binary Tree Right Side View(opens in a new tab) requires choosing breadth order and the visible node from each level.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Binary 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 |
|---|---|---|---|
| Profile n reachable nodes | O(n) | O(n) | Height h recursive frames; fixed-size profile output. Input array storage is excluded. |
| Collect breadth levels | O(n) | O(n) | O(w) queue width plus O(n) returned values; unreachable stored entries are not scanned. |
O(h) for profile n reachable nodes; O(n) for collect breadth levels.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Truthiness discards a valid zero node. The serialized absence marker is specifically None.
Prevent it: Use is not None when testing whether a stored node is present.
present = [value for value in values if value]present = [value for value in values if value is not None]Where you will hit this: Profile a Binary Tree(opens in a new tab)
An array entry is not automatically reachable. A missing parent disconnects all its descendants from the root.
Prevent it: Check parent reachability before accepting a non-root position.
reachable = values[index] is not Nonereachable = values[parent] is not None and values[index] is not NoneWhere you will hit this: Profile a Binary Tree(opens in a new tab)
Height follows one root-to-leaf path, so independent branch heights cannot be summed.
Prevent it: Add the current node to the maximum child height; use addition for counts instead.
height = 1 + left[1] + right[1]height = 1 + max(left[1], right[1])Where you will hit this: Binary Tree Right Side View(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27