Skip to contentKEEP THE CRAFTTHE SANCTUARY

Binary Tree

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…

Binary Tree Code Labs

Mental Model

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.

Node Shape and Base Cases

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.

Compute Bottom-Up Properties

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.

Aggregate a Binary Tree Profile

Reference
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))
Practice

Implement binary_tree_profile(level_order). Count reachable nodes, node-count height, and leaves in a complete-index array with None gaps.

Public tests

  • Verify reachable subtree aggregation

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

Aggregate a Binary Tree Profile

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))

Trace Reachable Subtree Return Values

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.
Print 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.

Traverse Level by Level

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.

Collect Reachable Tree Levels

Reference
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 levels
Practice

Implement binary_tree_levels(level_order). Return reachable values grouped by depth, ignoring entries below missing parents.

Public tests

  • Verify level boundaries and reachability

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

Collect Reachable Tree Levels

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 levels

Choose Recursive or Iterative State

Use 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.

Binary Subtree and Height Mistakes

  • Mixing edge-count and node-count height creates off-by-one answers.
  • Treating every non-None array entry as reachable accepts children of missing parents.
  • Recomputing subtree height inside every balance check can produce O(n squared) work.
  • Sharing a mutable result list across recursive calls leaks state between branches or test cases.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

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

OperationAverageWorstInterview note
Profile n reachable nodesO(n)O(n)Height h recursive frames; fixed-size profile output. Input array storage is excluded.
Collect breadth levelsO(n)O(n)O(w) queue width plus O(n) returned values; unreachable stored entries are not scanned.

Space

O(h) for profile n reachable nodes; O(n) for collect breadth levels.

Assumptions

  • Height h recursive frames; fixed-size profile output. Input array storage is excluded.
  • O(w) queue width plus O(n) returned values; unreachable stored entries are not scanned.

Invariants Worth Saying Aloud

  1. None marks absence; zero and other false-valued node labels are still present.
  2. Only descendants reached through present parents belong to the tree.
  3. An empty subtree returns count=height=leaves=0; a leaf has node-count height one.

When To Use Or Avoid Binary Tree

Use It When

  • Use postorder for one completed summary per subtree.
  • Use a deque with a frozen frontier length for level grouping.

Choose Another Tool When

  • Do not infer BST value ordering from binary child shape.
  • Use an explicit stack when a deep chain may exceed safe recursion depth.

Common Pitfalls

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

Mistaking a zero-valued node for absence

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.

Avoid

present = [value for value in values if value]

Use instead

present = [value for value in values if value is not None]

Counting a stored child below a missing parent

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.

Avoid

reachable = values[index] is not None

Use instead

reachable = values[parent] is not None and values[index] is not None

Adding subtree heights instead of choosing the longest path

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.

Avoid

height = 1 + left[1] + right[1]

Use instead

height = 1 + max(left[1], right[1])

Reviewed References

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