Skip to contentKEEP THE CRAFTTHE SANCTUARY

Tree

A rooted tree gives each non-root node one parent and one route from the root. Choose preorder to act before children, postorder to combine completed subtrees, or breadth order to group depth; a binary tree is only one specialization.

1 practice exercise2 interview problems

Recognize it when Input is an acyclic hierarchy with one parent per non-root node.

Checking your account…

Tree Code Labs

Mental Model

A rooted tree is a hierarchy with one root, one parent for every other node, and a unique path from the root to each node. Removing any parent-child edge separates one subtree. This makes subtree results independent and composable, even when nodes have more than two children.

Rooted Hierarchy and Subproblems

Define a recursive helper over one node’s complete subtree. Preorder performs node work before its children; postorder waits until every child result is ready. A tree needs no visited set when input already provides directed child lists and guarantees acyclicity.

The Python recursion model(opens in a new tab) still limits safe call depth, so an explicit stack is appropriate for a long chain.

Compare Traversal Orders

Traversal order is part of the algorithm, not presentation. Preorder is useful for propagation and serialization; postorder supports aggregation and deletion; breadth order groups equal depth. For ordered children, preserve their stated order when pushing onto a LIFO stack.

Compare Tree Traversal Orders

Reference
def traversal_orders(children, root):
    preorder = []
    postorder = []
    def visit(node):
        preorder.append(node)
        for child in children[node]:
            visit(child)
        postorder.append(node)
    visit(root)
    return preorder, postorder
Practice

Implement traversal_orders(children, root). Return preorder and postorder lists while preserving each node's authored child order.

Public tests

  • Verify traversal timing

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

Compare Tree Traversal Orders

def traversal_orders(children, root):
    preorder = []
    postorder = []
    def visit(node):
        preorder.append(node)
        for child in children[node]:
            visit(child)
        postorder.append(node)
    visit(root)
    return preorder, postorder

Trace Node Entry Separately from Subtree Completion

The existing recursive Lab visits root 0 with children 1 and 2. Entry and return happen at different times even for the same node: the root enters first but returns last after both independent child subtrees complete.

print(traversal_orders([[1, 2], [], []], 0)) followed by print(traversal_orders([[]], 0))

Step Executed statement State Why
1 preorder.append(node) node = 0; preorder = [0]; postorder = [] Entry records the parent before any child work.
2 visit(child); preorder.append(node) child = 1; preorder = [0, 1] Authored child order selects node 1 first.
3 postorder.append(node) node = 1; postorder = [1] The leaf has no pending children and can complete immediately.
4 visit(child); preorder.append(node); postorder.append(node) child = 2; preorder = [0, 1, 2]; postorder = [1, 2] The second child completes before the parent’s return.
5 postorder.append(node); return preorder, postorder node = 0; result = ([0, 1, 2], [1, 2, 0]) The parent completes only after every authored child.
Print Output
1 ([0, 1, 2], [1, 2, 0])
2 ([0], [0])

Preorder can carry ancestor decisions down; postorder can consume completed child results. This trace is an arbitrary-child tree contract, so the same loop must also handle a third or later child.

Derive Parent and Depth State

An undirected acyclic edge list becomes a rooted tree after choosing a root. Traverse once, skip the parent edge, and assign each child’s parent and depth. The parent check replaces a general visited set because a tree has no alternate route back to an earlier node.

Root an Undirected Tree

Reference
def parent_and_depth(node_count, edges, root):
    adjacency = [[] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].append(right)
        adjacency[right].append(left)
    parent = [-2] * node_count
    depth = [-1] * node_count
    parent[root] = -1
    depth[root] = 0
    stack = [root]
    while stack:
        node = stack.pop()
        for neighbor in adjacency[node]:
            if neighbor == parent[node]:
                continue
            parent[neighbor] = node
            depth[neighbor] = depth[node] + 1
            stack.append(neighbor)
    return parent, depth
Practice

Implement parent_and_depth(node_count, edges, root). Return parent and depth arrays after rooting the undirected tree; the root parent is -1.

Public tests

  • Verify parent and depth propagation

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

Root an Undirected Tree

def parent_and_depth(node_count, edges, root):
    adjacency = [[] for _ in range(node_count)]
    for left, right in edges:
        adjacency[left].append(right)
        adjacency[right].append(left)
    parent = [-2] * node_count
    depth = [-1] * node_count
    parent[root] = -1
    depth[root] = 0
    stack = [root]
    while stack:
        node = stack.pop()
        for neighbor in adjacency[node]:
            if neighbor == parent[node]:
                continue
            parent[neighbor] = node
            depth[neighbor] = depth[node] + 1
            stack.append(neighbor)
    return parent, depth

Choose a Tree Representation

Use node objects when recursive structure is supplied directly, child lists for arbitrary branching, an adjacency list for undirected edges, and parent arrays for ancestor/depth preprocessing. A binary tree specializes child count; a BST adds ordering. A graph is required when cycles or multiple paths are allowed.

Tree Parents and Traversal Timing Mistakes

  • Treating an undirected parent edge as a child causes immediate backtracking forever.
  • Using preorder when the answer depends on completed child results reads unfinished state.
  • Assuming every tree is binary drops later children.
  • Copying a full path at each node can create quadratic work on a chain.
  • Recursive code can exceed Python’s recursion limit even though the algorithm is O(n).

Explain It in an Interview

State the root, representation, and return contract for one subtree. Name why the chosen traversal order matches when information becomes available. Give O(n) time because each node/edge is processed once and O(h) recursive space or O(w) breadth frontier space.

Profile a Binary Tree(opens in a new tab) is one binary specialization. Binary Tree Level Order(opens in a new tab) tests whether breadth grouping is chosen instead of generic recursion.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
Preorder and postorder traversalO(n)O(n)n reachable nodes; stores two output lists and up to height h recursive frames. Python recursion depth remains bounded.
Build rooted parent/depth arraysO(n)O(n)Connected valid undirected tree has n-1 edges; adjacency, arrays and frontier use linear storage.

Space

O(n + h) for preorder and postorder traversal; O(n) for build rooted parent/depth arrays.

Assumptions

  • n reachable nodes; stores two output lists and up to height h recursive frames. Python recursion depth remains bounded.
  • Connected valid undirected tree has n-1 edges; adjacency, arrays and frontier use linear storage.

Invariants Worth Saying Aloud

  1. Child-list input describes a valid rooted tree; each reachable node is visited once.
  2. Preorder records entry, while postorder records only after all child visits return.
  3. An undirected-tree traversal skips the parent edge before assigning child state.

When To Use Or Avoid Tree

Use It When

  • Use child lists for arbitrary branching and an adjacency list for an undirected tree.
  • Choose traversal timing from when the needed information becomes available.

Choose Another Tool When

  • Use graph traversal with visited state when cycles or alternate paths are allowed.
  • Do not restrict a general tree to two children.

Common Pitfalls

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

Silently treating an arbitrary-child tree as binary

Taking only the first two child entries drops valid later subtrees.

Prevent it: Iterate every authored child unless the input contract is explicitly binary.

Avoid

selected = children[node][:2]

Use instead

selected = list(children[node])

Following an undirected parent edge as a child

An undirected neighbor list includes the parent. Re-enqueuing it reverses direction and can make parent/depth traversal cycle.

Prevent it: Exclude the current node's parent under a valid tree contract.

Avoid

next_nodes = list(adjacency[node])

Use instead

next_nodes = [neighbor for neighbor in adjacency[node] if neighbor != parent[node]]

Recording postorder before completed child results

A parent-first list is preorder. A subtree aggregate cannot be final until its child results are available.

Prevent it: Combine completed child postorders before appending the parent.

Avoid

postorder = [node]
for child_result in child_postorders:
    postorder.extend(child_result)

Use instead

postorder = []
for child_result in child_postorders:
    postorder.extend(child_result)
postorder.append(node)

Reviewed References

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