Data Structures & Algorithms practice
Data Structures & Algorithms ยท Hierarchical Structures

Trees & Traversals: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1Node And Reference, In A TreeEasyMust Do

A binary tree is made of nodes. Each node holds a value and two references, left and right, and each reference points to another node or is None (no child). DSA Topic 12's node had one reference, next; DSA Topic 8 let nested lists stand in for trees. Here the tree is built from real nodes.

Write a TreeNode class with __slots__, val, left and right. Then:

  1. Make seven nodes with values 1 to 7, one at a time, and keep them in a Python list as they are made.
  2. Link them by hand into three levels: node 1 on top with children 2 and 3, node 2 with children 4 and 5, node 3 with children 6 and 7. Add a comment on the first node.left = x saying what the assignment does.
  3. Name the parts on that tree and print each one with its values: the root (the one node no reference points to), a parent and its children, two siblings (children of one parent), the leaves (nodes with no child), the internal nodes (all the others), an edge (one parent-child link), and the subtree at node 2 (node 2 and everything below it).
  4. Count over the node list, with no traversal: n nodes have n - 1 edges, because every node but the root has exactly one parent, and of the 2n child references exactly n + 1 are None.
  5. Show that two names for one node see the same change, using is, and that two nodes with equal values are still two nodes.
Q2Building From A Level-Order ListEasyMust Do

A binary tree is easy to type as a level-order list: the root first, then each real node's two children in turn, level by level and left to right, with None for a missing child. A None has no children listed, so [1, 2, 3, None, 4] gives node 2 a missing left child and a right child 4, and stays compact. This is a way to write a tree down, not an index layout (the array layout with parent and child index arithmetic belongs to heaps, DSA Topic 15).

Write three functions for TreeNode (a node with val, left, right):

  1. from_level(values) builds the tree and returns the root. It hands children to parents through a queue (collections.deque, DSA Topic 11), and raises ValueError if a value has no parent to hang from.
  2. to_level(root) returns the list from_level reads: None for each missing child of a real node, with trailing Nones cut.
  3. show(root) returns a sideways picture: the root at the left edge, right children above, four spaces per level.

Check them: show [1, 2, 3, None, 4], round-trip 300 seeded random trees (to_level(from_level(a)) == a for every list a that to_level produced), and test [], [1] and two invalid lists.

Q3Every Shape Up To Seven NodesEasy

A tree shape is the pattern of children with the values left out. Write shapes(n), which returns every shape with n nodes as nested tuples (left_shape, right_shape), with None for the empty tree, and build(shape, values), which makes fresh TreeNodes in that shape taking values from an iterator in pre-order (node, then left, then right).

  1. shapes(n) puts k nodes on the left and n - 1 - k on the right for every k (recursion, DSA Topic 8).
  2. Print how many shapes there are for n = 0..9 and check each count against math.comb(2 * n, n) // (n + 1) (the Catalan numbers).
  3. Build ALL, every tree with 0 to 7 nodes, labelled 1 to n. Check on all of them that a tree with n >= 1 nodes has n - 1 edges and n + 1 None references, and that to_level and from_level round-trip.
  4. Say why testing every shape beats testing a few random ones, and what a dict memo would change in shapes.
Q4Depth, Height And DegreeEasy

This topic uses one set of words, so state them and compute them on a 9-node tree.

  • Depth of a node counts edges from the root: the root has depth 0.
  • Height of a tree counts nodes on its longest downward path: the empty tree has height 0, one node has height 1. (Height in edges is that number minus 1.)
  • Degree of a node is its number of children.
  • Level d is every node at depth d.

Depth flows down (pass d + 1 to the children) and height flows up (1 plus the larger child height). Write both recursively, with degree and a levels grouping, on the tree [1, 2, 3, 4, 5, None, 6, 7, None, None, 8, None, None, 9] (level-order list, as in from_level). Print them, print the height in edges once so the convention is explicit, and then check on all 626 trees with 0 to 7 nodes: height equals 1 plus the largest depth (non-empty trees), level sizes sum to n, level d holds at most 2^d nodes, and the degrees sum to n - 1.

Q5Three Orders From One WalkEasyMust Do

A recursive walk of a binary tree reaches each node three times: on the way down (before either subtree), between its two subtrees, and on the way back up (after both). Recording the node's value at the first moment gives pre-order (node, left, right), at the second in-order (left, node, right), at the third post-order (left, right, node). The empty tree has no nodes and gives an empty list in all three.

  1. Write walk(node, pre, ino, post), one recursive function that appends to the three lists at the three moments.
  2. Add a trace=True flag that prints enter, between and leave lines indented by depth, and trace it on the 7-node tree [7, 3, 5, 6, 1, 4, 2] (level-order list, so 7 is the root, 3 and 5 its children).
  3. Print the three lists, and say in one line each what the order is for.
  4. Write three separate one-order recursive functions and check that walk agrees with them on all 626 trees with 0 to 7 nodes. Also check that walk recorded exactly 3 events per node.
Q6What Pre-Order Is ForEasy

A parent must exist before its children can hang from it, so a copy of a tree is built in pre-order: make the new node first, then copy the left and right subtrees into it.

  1. Write clone(node), which returns a new tree with the same shape and values and leaves the original unchanged.
  2. Check on all 626 trees with 0 to 7 nodes and 200 seeded random trees (sizes 0 to 40): the copy's to_level equals the original's, the two trees share no node (compare id sets while both are alive), and changing the copy does not show in the original. Contrast this with alias = root, where a change does show.
  3. Write outline(root): pre-order with depth, giving the indented listing a table of contents uses. Print it for a 9-node tree.
  4. Name the other pre-order job here: writing a tree down with markers for missing children is also pre-order (built later in this topic).
Q7What Post-Order Is ForEasy

Some answers need the children's answers first, and that is post-order: visit the left subtree, the right subtree, then the node. A node's size is the number of nodes in its subtree and its sum is the total of their values.

  1. Write measure(node, size, total, calls), one post-order pass that stores every node's subtree size and sum in dicts keyed by value (values are distinct), and counts its calls in calls[0].
  2. Write the slow check: for every node start a separate count at that node (a level-order walk), counting the node visits.
  3. Run both on a seeded random tree of 1,500 nodes with distinct values and on a path of 800 nodes, and print the one-pass calls beside the brute-force visits. Assert both give the same dicts.
  4. Check the root's size and sum on all 626 trees with 0 to 7 nodes.
  5. Say where else post-order is the order: freeing (C must free a node's children before the node, or it loses the references to them; CPython frees a node when its last reference goes, so dropping the root of a tree with no parent links frees it all) and evaluating an expression (DSA Topic 8's nested expressions were evaluated this way).
Q8What In-Order Is ForEasy

In-order (left subtree, node, right subtree) lists the nodes in their left-to-right order across the page. Show it on the 9-node tree [6, 9, 2, 7, 4, 8, 1, 5, 3] (a level-order list).

  1. Number the nodes by their in-order position, and draw the tree top-down with each node's value at column index * 3 on the row of its depth. Also print the tree sideways, right side on top (this is the reverse in-order).
  2. Check on all 626 trees with 0 to 7 nodes that every node's column is greater than every column in its left subtree and smaller than every column in its right subtree, and that the columns are exactly 0 .. n - 1.
  3. For an expression tree, in-order gives the infix form, but it needs brackets that pre-order and post-order do not. Build the trees for (2 + 3) * 4 and 2 + (3 * 4), print their plain in-order text (no brackets), their pre-order and post-order, and their values.
  4. Say that a binary search tree's in-order is sorted (DSA Topic 14), that these trees hold arbitrary values (one assert shows this tree's in-order is not sorted), and that only binary trees have an in-order: a node with three children has no single "between".
Q9Level-Order With A QueueEasyMust Do

Level-order visits the nodes of a binary tree depth by depth: depth 0, then depth 1, then depth 2, each level left to right. The empty tree gives an empty list.

  1. Write level_order(root, trace=False) using a queue (collections.deque, DSA Topic 11) that holds the nodes found but not yet visited: pop from the front, visit, append the left then the right child. It returns the values and a stats dict with the number of pushes, pops and the peak queue length.
  2. Trace the queue's values step by step on the 9-node tree [5, 8, 3, 1, 9, None, 7, 4, 2, 6] (level-order list).
  3. Count real events: every node is pushed once and popped once, so pushes and pops both equal n. A tree has no node with two parents, so no visited set is needed (graphs do, DSA Topic 17).
  4. Check against an oracle: a recursive pre-order that appends each value to the list of its depth gives every level left to right, and the levels joined must equal the level-order. Run it on all 626 trees with 0 to 7 nodes and 300 seeded random trees.
Q10One Level At A TimeEasy

Level-order lists the values of a binary tree depth by depth. Often you need the levels separately. Read len(queue) at the start of a level and pop exactly that many nodes: everything appended meanwhile belongs to the next level (DSA Topic 11's layer-by-layer walk, now on a tree).

  1. Write levels(root), which returns the list of levels, each a list of values left to right ([] for the empty tree).
  2. From it compute the per-level counts, the per-level maxima and the widest level (the level with the most nodes; a tie goes to the shallower level, so the answer is deterministic; None for the empty tree).
  3. Show a tie: a tree whose level 1 and level 2 both hold two nodes.
  4. Check against the oracle (a recursive pre-order that groups values by depth) on all 626 trees with 0 to 7 nodes and 300 seeded random trees with values in 0 to 9, comparing levels, counts, maxima and the widest level.
Q11Size, Height And LeavesEasyMust Do

A binary tree is made of nodes, each holding a value and a left and a right reference that may be None. Three measures can each be computed by "combine the children's answers". The conventions, so nothing is left to guess:

  • The size of a tree is its number of nodes; the empty tree (None) has size 0.
  • The height counts nodes on the longest path from the root down; the empty tree has height 0 and a single node has height 1.
  • A leaf is a node with no children at all (a node with one child is not a leaf). The empty tree has 0 leaves.

Write three recursive functions, each taking a node (or None) and returning an int:

  1. size(node) = 1 + size(left) + size(right).
  2. height(node) = 1 + the larger of the two children's heights.
  3. leaves(node) = 1 at a childless node, otherwise leaves(left) + leaves(right).

Make the base case the empty tree, so a node with only one child needs no special case: show that on a two-node tree. Then check all three on every binary tree shape with 0 to 7 nodes (626 trees) against a level-order walk that uses no recursion: the level sizes add up to the size, the number of levels is the height, and a queue walk that counts childless nodes gives the leaves. Also check the bounds height <= size <= 2^height - 1 and leaves <= (size + 1) // 2. State time and space.

Q12Good Nodes: Passing The Path DownMedium

A node is good if its value is at least every value on the path from the root down to it (the root is always good). Count the good nodes of a binary tree in two ways.

  1. Brute force: from each node climb to the root through a parents dict (the kit's parents, pasted below with its contract) and compare. That is O(depth) per node, O(n h) in all.
  2. Pass the path down: carry the largest value seen so far as an argument. Each node compares once and hands the larger value on: O(1) per node, O(n) in all.

Count the steps each way (a step is one node touched) on a complete tree of 4,095 nodes, a random tree of 4,000 nodes and a path of 800 nodes (values seeded), and print the ratios. Then check both counts against each other on every shape with 0 to 7 nodes whose values are seeded in 0..3 (ties matter: equal counts as good).

Q13Recursion Depth Is The HeightMediumMust Do

A recursive function over a tree keeps one call open for each node on the path it is currently following (plus one for the empty child it has just reached), so its stack space is O(h), where h is the height (nodes on the longest root-to-leaf path): about log2(n) frames on a balanced tree and n frames on a path. CPython allows sys.getrecursionlimit() frames (1,000 by default) before it raises RecursionError.

Two builders will make the test trees, and you must explain both. path_tree(n) is a degenerate tree: n nodes in a line, each the left child of the one before, values 1..n. random_tree(n, rng) adds nodes one at a time, each into a free child slot chosen by the seeded rng.

  1. Write a recursive height(root) that also records the deepest call depth it reached (the root's call is depth 0, and each call into a child is one deeper, empty children included).
  2. Measure it on the complete tree built from list(range(1, 2**17)) (131,071 nodes), on random_tree(10**5, random.Random(13)) and on path_tree(800). Print each tree's size, height and deepest call depth beside sys.getrecursionlimit().
  3. Call it on path_tree(2000), catch the RecursionError and print only its type name.
  4. End with what is safe: recursion on trees whose height is far below the limit, and not on degenerate ones.
Q14Pre-Order With A StackEasy

DSA Topic 8 turned a pre-order walk of nested lists into an explicit stack. On a binary tree the rule is: pop a node, visit it, push its right child and then its left child, so the left comes off first. Pre-order means node, left, right.

  1. Write pre_stack(root) returning the values and the stack's peak size, and a recursive pre_rec(root) as the oracle. Check both on all 626 shapes with 0 to 7 nodes.
  2. Show the usual bug: push the left child first. Print the wrong order beside the right one on the smallest tree that shows it.
  3. Measure the peak stack on the complete tree of 2^17 - 1 nodes, on random_tree(10**5) and on a left path and a right path of 10^5 nodes. The hypothesis: about the height on a bushy tree, and 1 on either path, because a path node's one child takes its place.
  4. The stack version finishes on path_tree(10**5); the recursive one raises RecursionError (caught).
Q15In-Order With A StackMediumMust Do

In-order on a binary tree means: the whole left subtree, then the node, then the whole right subtree. Write in_stack(root) with an explicit stack instead of recursion: push the whole left spine (the node, its left child, that node's left child, and so on until None); pop a node and visit it; then do the same from its right child.

  1. Return the values plus counts of pushes, pops and the peak stack size. Each node is pushed once and popped once, so the walk is O(n) even though one step may push many nodes: count the events where they happen and assert pops == pushes == n.
  2. Trace the stack's values (bottom to top) just before every visit on the seven-node tree [7, 3, 5, 6, 1, 4, 2] in level order (its in-order is not sorted: these trees hold arbitrary values).
  3. Check against a recursive in-order on all 626 shapes with 0 to 7 nodes and on 300 seeded random trees with 0 to 300 nodes.
  4. Measure the peak on the complete tree of 2^17 - 1 nodes, on random_tree(10**5) and on a left path and a right path of 10^5 nodes. The hypothesis: the stack holds the nodes still waiting for their right side, at most the height, so a left path fills it with every node and a right path never holds more than one.

State time and space.

Q16Post-Order With Two StacksMedium

Post-order is left, right, node. It is the reverse of a node, right, left walk, so a simple way to get it: the first stack runs a pre-order-style walk that pops a node, moves it to a second stack, and pushes its left and then its right child; popping the second stack then yields post-order. DSA Topic 8's processed flag is the other way to do it. The catch: the second stack ends up holding every node.

  1. Write post_two(root) returning the values and both stacks' peak sizes, and a recursive post_rec as the oracle. Check all 626 shapes with 0 to 7 nodes.
  2. Measure both peaks on the complete tree of 2^17 - 1 nodes, on random_tree(10**5) and on a left path of 10^5. The hypothesis: the second stack always reaches n, and the first stays small.
  3. State the cost: O(n) time, and O(n) space whatever the shape.
Q17Post-Order With One StackMedium

Post-order (left, right, node) with one stack of the current path. Keep a reference last to the node visited most recently. Walk down the left spine pushing nodes; then look at the top: if it has a right child that was not just visited, walk into that right child; otherwise visit the top, pop it and set last to it.

  1. Write post_one(root) returning the values and the peak stack size, and check it against a recursive post-order on all 626 shapes with 0 to 7 nodes and 300 seeded random trees. The stack holds only the current path, so the peak is at most the height: O(h), which is n on a path.
  2. Measure the peak on the complete tree of 2^17 - 1 nodes, on random_tree(10**5) and on a left and a right path of 10^5.
  3. Show the bug of leaving out the last check: the walk enters the right side again and again. Run it with a step budget (a counter that raises after 10^4 steps, caught) on the smallest shape that fails, and print that it never finished.
Q18Mirroring A TreeEasy

Mirror a binary tree by swapping the two children at every node. Write it two ways, both changing the tree in place (no node is created) and returning the same root: recursively, and with a queue.

  1. Mirroring twice must give back the original (to_level equal), and the set of node identities must be unchanged. Check both on all 626 shapes with 0 to 7 nodes and on 200 seeded random trees.
  2. The mirror's pre-order is the original's node, right, left order, and its in-order is the original's in-order reversed. Check both on all 626 shapes (take the original's lists before mirroring).
  3. Show a seven-node tree before and after with show. State time and space for both versions. The queue version also finishes on a path of 10^5 nodes.
Q19Are Two Trees The SameEasy

Two binary trees are the same when they have the same shape and the same values: both are empty, or both are non-empty with equal values at the root and the same left subtrees and the same right subtrees.

  1. Write same_tree(a, b) returning (answer, calls), where calls counts every comparison of a pair of positions made. It must stop at the first difference: show the count for identical trees, for trees differing at the root, and for trees differing only at the deepest left leaf of a complete tree of 255 nodes.
  2. Equal pre-orders do not mean equal trees. Print two trees with the same pre-order but different shapes (2 as the left child of 1, and 2 as the right child of 1), and note that writing a tree down needs markers for the missing children.
  3. == on two TreeNodes compares identity, not contents. Print that.
  4. Check against to_level equality on every pair of shapes with 0 to 4 nodes (23 shapes, 529 pairs), once with values labelled in pre-order and once with seeded values in 0..2. State time and space.
Q20Searching Without An OrderEasy

In a binary tree whose values follow no rule, either side may hold the value you want, so a search may have to look at every node: O(n) in the worst case. It stops as soon as it finds the value. A binary search tree keeps smaller values on the left so that a search follows a single path in O(h): that is DSA Topic 14, and nothing here is built that way.

  1. Write find_rec(root, target) and find_stack(root, target), each returning (node, visited). They return the node (so the caller can use it), the first one in pre-order when values repeat, and None if the value is absent. visited counts the nodes looked at.
  2. On a random tree of 2,000 nodes with distinct values, count the nodes visited for a target at the root, at the last node in pre-order (the worst case for a value that is there) and for an absent target.
  3. Use a returned node: print its value's children.
  4. Check both against a brute force (scan the pre-order list of nodes for the first match) on every shape with 0 to 7 nodes, values seeded in 0..3 so that repeats are common, and targets -1 to 4. State time and space.
Q21Root-To-Leaf PathsEasyMust Do

Write root_to_leaf_paths(root) for a binary tree of TreeNodes (val, left, right; root may be None). It returns a list holding one list of values for every root-to-leaf path, left to right, and never changes the tree. A leaf is a node with no children at all: a node with one child is not a leaf, so a path may only end where both references are None. The empty tree has no paths ([]); a single node has one path, [val].

  1. Keep one path list for the whole walk. Append a node's value on the way down, record path[:] (a copy, because the list keeps changing) when the node is a leaf, and pop on the way back up. DSA Topic 19 generalises this append, recurse, pop shape (named only).
  2. Write an iterative version with a stack of (node, depth): before using a popped node, cut the path back with del path[depth:].
  3. Count the paths and the values written. The number of paths equals the number of leaves, and the output holds the sum of (depth + 1) over the leaves. On a caterpillar (a spine with one leaf hanging off every spine node but the last) that sum grows like n^2: print it at two sizes.
  4. Check both versions against an oracle that climbs the kit's parents dict (a dict from each node to its parent) from every leaf, on all 626 shapes with up to seven nodes. Run path_tree(10**5) through the iterative version and path_tree(2000) through the recursive one.

State time and space.

Q22A Path With A Given SumEasy

Write has_path_sum(root, target): is there a root-to-leaf path whose values add up to target? A leaf has no children at all; a node with one child is not a leaf. The empty tree has no paths, so the answer is False for every target. Values may be negative.

  1. Pass the remaining target down (target - node.val) and compare it with 0 only at a leaf.
  2. Write the tempting wrong version that stops as soon as the remaining target goes below 0. Search all 626 shapes (seeded values in -3..3, targets -10..10) for the smallest failing case, and print it with show() beside the truth.
  3. Write an iterative version with a stack of (node, remaining).
  4. Check all three against the sums of the enumerated root-to-leaf paths (found by climbing the kit's parents dict from each leaf). The correct versions must never fail; the wrong one must fail at least once.

State time and space.

Q23Memory Per NodeMedium

A tree of a million nodes is a million objects, so what one node costs matters. Measure it.

  1. Build a left path of 10^5 nodes five ways and one more, every node holding the same value object so only the node itself is counted: the slotted TreeNode, a plain class with no __slots__, a (val, left, right) tuple, a [val, left, right] list, a dict, and an NNode (the kit's N-ary node) with one child each. Use tracemalloc and divide the bytes by the node count.
  2. Hypotheses to test: slots save about 40% against the plain class, and the dict costs about three times the slotted node. Print the measured saving and ratio, and conclude from those printed numbers.
  3. Print sys.getsizeof for a slotted and a plain node beside the measured bytes, and say why the plain figure under-counts.
  4. In a seeded random tree of 1,000 nodes count the None references: of the 2n child references, n + 1 hold nothing.

No timing verdict here: bytes only. DSA Topic 12 measured one-reference nodes the same way.

Q24Copying A TreeMedium

Make three copies of a binary tree and check each one.

  1. A recursive pre-order clone: make the new node first, then clone the left and right subtrees into it (the parent must exist before the children can hang from it).
  2. An iterative clone with a stack of (original, copy) pairs, which works at any depth.
  3. copy.deepcopy.
  4. Check each on all 626 shapes with up to seven nodes (values 1..n): to_level equal, the sets of node ids disjoint while both trees are alive, and a change to the copy's root not visible in the original.
  5. Measure: deepcopy on a path of 100 nodes and on a path of 400 (hypothesis: the 400 raises RecursionError, since deepcopy spends several frames per level; print the type name only). Then time deepcopy against the iterative clone on a seeded random tree of 30,000 nodes (min of 3 each), and give a verdict only when the ratio is at least 2x.

DSA Topic 8 copied nested data with a memo and DSA Topic 12 showed deepcopy failing on a long chain: here the shape is a tree. State time and space for each.

Q25Which Traversal WhenMedium

Eight tasks, each matched to the order that fits before any code is written, then solved once on one seeded random tree of 10^4 nodes (random_tree(10**4, random.Random(13)), values 0..n-1 in creation order, all distinct), counting the nodes each solution visits.

  1. Outline: print every node indented by its depth (pre-order: a parent before its children).
  2. Every subtree's size (post-order: the children's answers first).
  3. Free the tree in C's order, simulated by recording the order (post-order: free the children before the parent, or the references to them are lost).
  4. List the values left to right (in-order).
  5. The largest value on each level (level-order, one len(queue) slice per level).
  6. Write the tree down with # for each missing child (pre-order), which makes 2n + 1 tokens.
  7. Evaluate a small expression tree for (2 + 3) * (8 - 4) (post-order).
  8. Is any node deeper than k? (any order; stop at the first hit), tried for k = 4 and for k = the tree's depth.

Check each result against something independent, then print one table: task, order, why, nodes visited. Close with a sentence built from the visit counts.

Q26Minimum DepthEasy

The minimum depth of a binary tree is the number of nodes on the shortest root-to-leaf path: one node gives 1, the empty tree gives 0. A leaf has no children; a node with one child is not a leaf, so that path cannot stop there.

  1. Write the tempting wrong version, 1 + min(left, right) at every node, and print the smallest shape (over all 626) where it disagrees with the truth.
  2. Write the correct recursion: with one child missing take the other child's answer, take the smaller only when both children exist.
  3. Write a level-order version that returns at the first leaf it pops.
  4. Count the nodes each version visits on a seeded random_tree(10**4), on the complete tree of 2^14 - 1 nodes, and on that complete tree with one node at depth 2 cut down to a leaf.
  5. Check both against the shortest root-to-leaf path found by enumerating every leaf's depth, on all 626 shapes.

State time and space.

Q27Symmetric TreesEasyMust Do

Write is_symmetric(root) for a binary tree of TreeNodes (val, left, right; root may be None). A tree is symmetric when it equals its mirror, where the mirror swaps the left and right child at every node. The function returns True or False, never changes the tree and builds no mirror. The empty tree is symmetric, and so is a single node.

  1. Compare the left subtree with the right subtree: two subtrees a and b mirror each other when both are empty, or both exist with equal values and a.left mirrors b.right and a.right mirrors b.left.
  2. Write it recursively, then with a deque of (a, b) pairs.
  3. Check against a built mirror (a new tree with the children swapped everywhere): is_symmetric(t) must equal to_level(t) == to_level(mirror_copy(t)) on all 626 shapes with seeded values, and on trees symmetric by construction.
  4. Count the symmetric shapes (all values equal) for every n from 0 to 9, by checking all 6,918 shapes.
  5. Show that equal subtrees are not mirrored subtrees (the shapes must mirror and the values must match), and that on a symmetric path-pair of 2000 nodes per side the recursion raises RecursionError while the queue answers.

State time and space.

Q28Checking Balance, NaivelyMedium

A tree is height-balanced when at every node the heights of the two subtrees differ by at most 1 (height counts nodes: the empty tree is 0, one node is 1).

  1. Checking only the root is wrong. Search all 626 shapes for the smallest tree whose root passes while the tree is not balanced, and print it with show().
  2. Write the direct check: call height() on both sides of every node. Count the height calls (empty children included) on complete trees of 2^k - 1 nodes for k = 8..12 and print calls per node and the growth when n doubles. Compare calls with n * log2(n + 1).
  3. Count the calls on paths of 400 and 800 nodes: the check fails at the root and stops after about 2n calls, so it is not quadratic there. Its cost depends on the shape.
  4. Check it against an independent iterative oracle (heights from reversed pre-order) on all 626 shapes and 300 seeded random trees, empty tree included. A one-pass version is the next step.

State time and space.

Q29Checking Balance In One PassMediumMust Do

Write is_balanced(root) for a binary tree of TreeNodes (val, left, right; root may be None). The tree is height-balanced when at every node the heights of its left and right subtrees differ by at most 1, where the height counts nodes (the empty tree is 0, a single node is 1). Checking the root alone is not enough: every node must pass. The function returns True or False and never changes the tree. The empty tree and a single node are balanced.

  1. Write a helper that returns the subtree's height, or -1 as soon as any node below is unbalanced. Check the left side first and skip the right side when the left returned -1: each node is then visited at most once.
  2. Count the calls (empty children included) on complete trees of 2^k - 1 nodes for k = 8..12 beside the naive check that calls a separate height() at every node, then on a left path of 400 nodes and on a seeded random_tree(4000), where the early exit stops after a few dozen calls.
  3. Write an iterative version (heights from reversed pre-order, any depth) and run it on path_tree(10**5) and on the complete tree of 2^17 - 1 nodes. Show the recursive one raising RecursionError on a path of 2,000.
  4. Check all against the definition (a separate check of both subtree heights at every node) on all 626 shapes with up to seven nodes and on 300 seeded random trees, including the empty tree.

State time and space. Returning one value that carries two facts, a height or "no", is a single post-order pass. DSA Topic 21 calls this DP on trees.

Q30The DiameterMediumMust Do

Write diameter(root) for a binary tree of TreeNodes (val, left, right; root may be None). The diameter is the number of edges on the longest path between any two nodes (the path may go up and then down, and it need not pass through the root). The empty tree and a single node have diameter 0. Height counts nodes (empty 0, one node 1). The function returns an int and never changes the tree.

  1. Find the smallest shape (over all 626 with up to seven nodes) whose diameter is larger than height(left) + height(right) taken at the root, and print it with show(): the longest path avoids the root.
  2. Naive: at every node compute height(left) + height(right) (the edges of the longest path whose highest node is this one) and keep the largest. Count the height calls on paths of 400 and 800 nodes (about four times the calls for twice the nodes) and on complete trees.
  3. One pass: a helper returns the height, and updates a best left + right on the way up. Count its calls (2n + 1, empty children included).
  4. Write an iterative version (reversed pre-order, any depth) and run it on path_tree(10**5).
  5. Check all three against a brute force over every pair of nodes (the distance through the kit's parents dict) on all 626 shapes and 300 seeded random trees, empty tree included.

State time and space. It returns a height up in post-order, like the one-pass balance check.

Q31Level Sums And AveragesEasy

A level is every node at one depth (the root is at depth 0). The layer-by-layer walk from DSA Topic 11 becomes level-order on a tree: before a level is processed, len(queue) is exactly the number of nodes on that level, so a loop of that many popleft calls handles one level and leaves the next level's children waiting behind it.

Write level_stats(root) that returns, for each level from the top, a tuple (sum, count, maximum) of the values on that level (an empty list for the empty tree). Then:

  1. Print the sum, the average (to 2 decimals) and the maximum of every level of the tree from_level([5, 3, 8, 1, 4, None, 9, 2]), drawn with show.
  2. Report the sum of the deepest level, and the level with the largest sum. On a tie the shallower level wins (state this rule in the function). Show the tie rule on from_level([1, 3, 2, 5]), where levels 1 and 2 both sum to 5, and show what the >= version returns instead.
  3. Check level_stats on all 626 shapes with up to seven nodes (values drawn from a seeded generator, between -9 and 9) and on 300 seeded random trees of 0 to 60 nodes, against an oracle that walks with a stack, carries each node's depth, and groups the values by depth. A crash counts as a failure.
  4. State time and space, and say what replaces this in Python. Nothing does: Python has no tree type.
Q32Zigzag Level OrderMedium

Zigzag level order lists the levels from the top, the root's level left to right, the next right to left, and so on, alternating. For from_level([1, 2, 3, 4, 5, 6, 7]) it is [[1], [3, 2], [4, 5, 6, 7]].

Write three functions that return the list of levels in zigzag order, each one a different way to get the order of the odd levels:

  1. zig_reverse(root): plain level-order with the len(queue) rule, then reverse every level at an odd depth.
  2. zig_deque(root): build each level in a deque (DSA Topic 11), appending on the right at even depths and on the left at odd depths, so no list is reversed afterwards.
  3. zig_stacks(root): two stacks (DSA Topic 10) that swap roles at each level. Popping a stack reverses the order in which it was pushed, so each node pushes its children in the order that the next level's pops need.

Print all three on a 10-node tree drawn with show, then check them against an oracle that groups the values by depth in left-to-right order (a pre-order walk with depths) and reverses the odd depths. Run it on all 626 shapes with up to seven nodes and on 300 seeded random trees of 0 to 60 nodes. A crash counts as a failure. State time and space for each.

Q33The Right Side ViewMedium

Standing to the right of a binary tree and looking left, you see one node per level: the rightmost node on that level. The right side view is those values from the top level down. (The left side view is the leftmost node of each level.)

Write two functions that return the right side view of a tree (an empty list for the empty tree):

  1. right_view_level(root): level-order with the len(queue) rule, keeping the last node of each level.
  2. right_view_dfs(root): a depth-first walk that visits the node, then the right child, then the left child, and records a node's value when its depth has not been seen before (the first node reached at each depth is the rightmost one).

Then:

  1. Left view by two routes: left_view_level takes the first node of each level, and the left view must also equal right_view_dfs of a mirrored copy of the tree. Write mirror_copy(root), which returns a new tree with every pair of children swapped and leaves the input unchanged.
  2. Check all three agree on all 626 shapes with up to seven nodes and on 300 seeded random trees of 0 to 60 nodes. A crash counts as a failure.
  3. Measure the space of each method from counters inside the walks: the largest queue length for level-order and the deepest recursion (in frames) for the depth-first walk, on a complete tree of 4,095 nodes and on a left path of 500 nodes. Say which one uses less space on each shape, taken from the counted numbers.
Q34Lowest Common AncestorMediumMust Do

In a binary tree, the lowest common ancestor (LCA) of two nodes p and q is the deepest node that has both of them in its subtree, where a node counts as being in its own subtree. So if p is an ancestor of q, the LCA is p itself. p and q are given as nodes (references, not values: values may repeat), and both are in the tree. The root is the ancestor of everything, so an LCA always exists.

Write lca(root, p, q) that returns the LCA node, in one post-order pass: an empty subtree returns None; a node that is p or q returns itself without looking further down; otherwise ask both children, and if both answered, this node is the LCA; if only one answered, pass its answer up.

  1. Draw a 7-node tree with show and print the LCA values of a few pairs, including a pair where one node is an ancestor of the other, and p with itself.
  2. Show why the comparison must be by identity: on a tree whose nodes all hold the value 7, a version that compares node.val to p.val returns the wrong node. Print both answers as pre-order positions and assert that they differ.
  3. Check lca against an oracle that finds the path from the root to each node using a parents dict (a dict from each node to its parent, built level by level) and takes the last node the two paths share. Test every pair of nodes (including a node with itself) in every shape with up to 6 nodes, and 200 seeded random trees of 1 to 40 nodes with 15 random pairs each. A crash counts as a failure, and the run must have met both an ancestor pair and a p is q pair.
  4. State time and space. What changes when one of the nodes is not in the tree is a harder question; here both are always present.
Q35LCA With Parent PointersMedium

A tree node knows its children but not its parent. A parents dict (a dict from each node to its parent, the root mapping to None, built once by a level-by-level walk in O(n)) fixes that: after it, a node can climb toward the root in O(1) per step. The lowest common ancestor of nodes p and q (the deepest node with both in its subtree, a node being in its own subtree) can then be found by climbing.

  1. Explain and build parents, and a depth dict (edges from the root) from it in O(n), using the fact that a node's parent appears before it in the dict.
  2. Write lca_climb(up, depth, p, q): lift the deeper node up until the depths match, then climb both together until they meet. It returns the node and the number of climbing steps taken: O(h) time per query and O(1) extra space.
  3. Write lca_set(up, p, q): put every ancestor of p (and p) in a set, then climb from q until a node is in the set: O(h) time and space.
  4. Run 100 seeded queries on random_tree(10**4) with each of: the one-pass search (O(n) per query in the worst case, with a counter for the nodes visited), the climb and the set method. All three must return the same node each time. Print the total steps of each, the average per query, and which is smallest, taken from the counters.
  5. Name what answers many queries at once offline: Tarjan's method uses union-find (DSA Topic 18), named only here.
Q36All Paths With A Given SumMedium

A root-to-leaf path starts at the root and ends at a leaf (a node with no children; a node with one child is not a leaf). Write paths_with_sum(root, target) that returns every root-to-leaf path whose values add up to target, each as a list of values, in left-to-right order. The empty tree has no paths.

  1. Build the naive version first: each call passes path + [node.val], a new list. Count the elements copied across all calls.
  2. Then the version with one shared list: append the node's value on the way down, record a copy of the list at a matching leaf, and pop on the way back up. Count the elements copied again. On a left path of 500 nodes (every value 1, target 500) both return the same one path; print both counts and check them against the formulas.
  3. Check it against an oracle that lists every root-to-leaf path by concatenation and keeps those with the right sum, on all 626 shapes with seeded values from -2 to 2 and every target from -6 to 6. A crash counts as a failure, and the run must have found some matches and some empty answers.
  4. State time and space. The shape "choose, recurse, undo" is the one DSA Topic 19 calls backtracking.
Q37Downward Paths With A Given SumHard

A downward path starts at any node and goes down through children to any descendant of it, or stops at that node itself; it need not start at the root or end at a leaf. Count the downward paths whose values add up to target. Values may be negative or zero, so a path can keep going after it hits the target.

  1. Naive: start a walk at every node and count the matches below it. Count the nodes visited: O(n h) in all (a node is visited once from each of its ancestors and itself).
  2. Better: this is DSA Topic 6's "subarray sum equals k" on the path from the root to the current node, with DSA Topic 7's dict of prefix counts. Keep counts, the number of times each prefix sum has occurred on the current root path, starting with {0: 1}. At a node with running prefix cur, the downward paths ending at this node and summing to target number counts[cur - target]. Add cur to counts on the way down and remove it on the way back up, so the dict describes only the current root path. O(n) time, O(h) space.
  3. Print the steps of both on a left path of 500 nodes (all values 1, target 3) and on random_tree(4000) with seeded values between -3 and 3 (target 3). They must return the same counts. Check the naive step count against the number of (ancestor-or-self, node) pairs.
  4. Show the bug of not removing the prefix on the way back: find, by search over small shapes, the smallest tree where the no-undo version miscounts, draw it with show, and print both counts beside the true one.
  5. Fuzz against an all-pairs check (each node against each ancestor-or-self, summing the values down to it through a parents dict) on all 626 shapes with seeded values between -2 and 2 and targets -3 to 3, and on 100 seeded random trees. A crash counts as a failure.
Q38The Maximum Path SumHard

A path here runs between any two nodes of a binary tree along the tree's edges (it may turn at one node, go up and then down, and need not touch the root; a single node is a path). The maximum path sum is the largest sum of the values on any path with at least one node. Values may be negative. The empty tree has no path: return None.

  1. One pass, like the diameter: each call returns the best downward sum that starts at its node and goes down one side, counting a child's gain only when it is positive (max(0, gain)), and updates a running best with node.val + left_gain + right_gain, the best path that turns at this node.
  2. Show the two bugs a student writes. Starting the best at 0 instead of "nothing yet" returns 0 on an all-negative tree, when the answer is the largest single value (print both on from_level([-3, -1, -2])). Taking a negative child's gain instead of 0 miscounts on from_level([1, -5, 3]): print each wrong answer beside the truth, and assert they differ.
  3. Check it against brute force: for every pair of nodes (a node with itself included), sum the values on the path between them using a parents dict (the dict from each node to its parent), and take the maximum. Test every shape with up to 6 nodes with three seeded value assignments each (values -4 to 4), and 100 seeded random trees of 1 to 30 nodes. A crash counts as a failure.
  4. State time and space.
Q39Root-To-Leaf NumbersEasy

In a binary tree whose values are digits 0 to 9, each root-to-leaf path spells a number: the path 1, 2, 3 is 123, and a leading 0 just adds nothing (0, 5 is 5). A leaf has no children. Write sum_numbers(root) that returns the sum of all those numbers (0 for the empty tree).

  1. Pass the value so far down: at each node so_far * 10 + digit; at a leaf, return it; otherwise add what the two sides return.
  2. Draw from_level([4, 9, 0, 5, 1]) with show and print the three numbers it spells (495, 491, 40) and their sum.
  3. Python's int is unbounded. A C long holds at most 2^63 - 1 (19 digits), so a path of 30 digits would overflow it. Show a 30-digit path tree and its value, and print whether it exceeds 2^63 - 1.
  4. The recursion is one frame per level. Write the same with an explicit stack of (node, so_far), and show that on a path of 3,000 digits the recursive version raises RecursionError and the stack version answers (print the digit count, never the depth where it fails). Do not time anything here: the numbers are 3,000 digits long.
  5. Check both against joining the digits of each enumerated path into a string and summing int(...) of them, on all 626 shapes with seeded digits and on 200 seeded random trees. A crash counts as a failure.
Q40Leaves Left To RightMedium

A leaf is a node with no children. Two trees are leaf-similar when their leaves, read from left to right, form the same sequence of values, whatever the shapes of the trees. Two empty trees are leaf-similar, and a one-node tree has one leaf: the node itself.

  1. Collect both leaf lists and compare: O(n) time, but O(L) extra space (L = the number of leaves).
  2. Walk both trees at once with explicit stacks, one leaf at a time: next_leaf(stack) pops until it reaches a leaf and returns its value (the stack holds the pending right siblings, so it never grows beyond the height plus one), or a sentinel when the tree has no leaf left. Compare leaf by leaf and stop at the first difference.
  3. Count the leaves read, and the longest stack, on two trees built to have the same leaves in different shapes: a complete tree of 4,095 nodes and a right-leaning chain of 2,048 leaves. Compare equal trees (all leaves read) with trees that differ at the very first leaf (two reads), and print the collected lists' sizes beside them.
  4. Check the stack walk against the list comparison on every pair of shapes with up to 5 nodes (65 trees, 4,225 pairs), with seeded values from 0 to 2, so many pairs are similar. A crash counts as a failure, and the run must have seen both similar and different pairs.
Q41Building From Pre-Order And In-OrderMediumMust Do

A binary tree with distinct values can be rebuilt from two lists of its values: the pre-order (the node, then the whole left subtree, then the whole right subtree) and the in-order (the whole left subtree, then the node, then the whole right subtree). The pre-order starts with the root; in the in-order, everything left of the root belongs to the left subtree and everything right of it to the right subtree. So the root's place in the in-order splits both lists, and each half is built the same way.

Write build_fast(pre, ino) that returns a new tree (it changes nothing it is given) and raises ValueError when the lists do not hold the same distinct values or do not describe one tree. Then:

  1. Write the naive build_slow(pre, ino, stats) first: find the root with a scan and cut both lists with slices. Count every comparison made by the scan in stats["compares"].
  2. Improve it: build a dict from value to in-order position once (DSA Topic 7), pass index bounds instead of slices, and read the pre-order once from an iterator. Count dict lookups and calls (2n + 1 calls: one per node and one per empty child).
  3. Compare the counts on a left path of 800 nodes, a right path of 800 nodes and a complete tree of 1,023 nodes.
  4. Rebuild every shape of 0 to 7 nodes (626 trees) and 300 seeded random trees of 0 to 300 nodes, and compare level-order lists. The harness catches every exception and counts it as a failure.
  5. Show that repeated values break the idea: two different trees with the same pre-order and the same in-order.
  6. Show what a path of 2,000 nodes does to the recursive builder, against the recursion limit.

State time and space for both builders.

Q42Building From Post-Order And In-OrderMedium

The post-order lists the left subtree, then the right subtree, then the node, so its last value is the root. Together with the in-order (distinct values) it fixes a tree, as the pre-order does. Reading the post-order from its end gives the root, then the whole right subtree, then the whole left subtree.

Write build_post(post, ino, right_first=True) that returns a new tree and consumes the post-order from its end. Then:

  1. Build with a dict of in-order positions and index bounds (as the pre-order builder did), reading reversed(post) once.
  2. Show the classic bug: build the left subtree first. Scan the 626 shapes of up to 7 nodes in increasing size, print the smallest tree that comes out wrong beside the truth, and count how many shapes go wrong.
  3. Check the correct builder on all 626 shapes and 300 seeded random trees of 0 to 300 nodes. The harness catches every exception and counts it as a failure.

State time and space.

Q43When Two Traversals Are Not EnoughHard

Not every pair of traversals fixes a tree. Pre-order with in-order does (distinct values), and so does post-order with in-order. Pre-order with post-order does not: a node with one child cannot tell whether the child is a left or a right one. A tree is full when every node has 0 or 2 children; for full trees the pair does work.

  1. Print two trees, one with a left child 2 under 1 and one with a right child 2 under 1, that share both their pre-order and their post-order.
  2. Count it. Label every shape of n nodes 1..n in pre-order, so every pre-order is the same, and count the distinct post-orders for n = 1 to 8 beside the number of shapes.
  3. Write build_full(pre, post) for full trees and check it on every full shape with up to 9 nodes. Count the full shapes and compare them with the Catalan numbers, and check that none exist with an even node count.
  4. Label every shape in level order instead and count the distinct in-orders. If they are all distinct, the pair (level-order, in-order) fixes the tree among those labelled shapes.

Counting is O(n^2) or worse and is fine for these sizes.

Q44Serialising With Null MarkersMediumMust Do

To save a binary tree as text, write its values in pre-order (the node, then the whole left subtree, then the whole right subtree) and write # for every empty child. Tokens are joined with commas, so the tree 1 with left child 2 and right child 3 becomes 1,2,#,#,3,#,#. A tree of n nodes writes 2n + 1 tokens: n values and n + 1 markers (every node has two child slots, 2n slots in total, of which n - 1 hold nodes). The empty tree is #. Values are ints, possibly negative or several digits long.

The text reads back in one pass: a value makes a node and then reads its left child and its right child; # is an empty child. Write:

  1. serialise(root, stats=None) with an explicit stack, so a path of 100,000 nodes works. Count the values and markers it writes, and assert that both match the formula.
  2. deserialise_rec(text) over an iterator of tokens (O(h) frames).
  3. deserialise_iter(text) with an explicit stack.
  4. Both readers raise ValueError, never another exception, for a missing token, a token left over, a non-number or an empty string. Split with str.split.
  5. Round-trip all 626 shapes of up to 7 nodes and 300 seeded random trees of 0 to 300 nodes with values from -1,000 to 1,000,000. The harness catches every exception and counts it as a failure.

State time and space.

Q45Serialising Level By LevelMedium

The level-order list from earlier in this topic (to_level and from_level: values level by level, None for every missing child of a real node, trailing Nones cut) is also a text format. Write to_text(root) (the entries joined by commas, # for None) and from_text(text), then study how long the text is:

  1. Round-trip all 626 shapes of up to 7 nodes and 300 seeded random trees of 0 to 300 nodes. Damaged text (a non-number, an entry with no parent) raises ValueError.
  2. A path is long in this format. Measure the number of entries for a left path of 50, a right path of 50 and a complete tree of 63, and state the formulas in n.
  3. Over the 626 shapes, check that the number of entries is between n and 2n - 1, count the shapes at each extreme, and compare it with the null-marker format (pre-order with # for every empty child, 2n + 1 tokens): for how many shapes is the level format shorter?
  4. Compute, as a number and without building anything, how many slots a layout with fixed positions for every possible node would need for a path of 50 nodes.
Q46N-ary TreesEasy

Not every tree has two children per node. A file system folder has any number. An N-ary tree node holds a value and a list of children, in order. Write NNode and from_nested, which turns ("a", [("b", []), ("c", [("d", [])])]) into nodes. Then:

  1. Write recursive size, height (counting nodes: the empty tree is 0, one node is 1), leaves (nodes with no children) and max_degree (the most children any node has), and recursive pre_order and post_order with a loop over the children. There is no in-order: with three children there is no single place "between".
  2. Write one level-order pass with a queue that returns the same four numbers and the level-order values.
  3. Show why the children list must be made fresh for every node: a class with children=[] as a default shares one list between nodes.
  4. Check the recursive and the queue versions against each other on 300 seeded random N-ary trees (each new node attaches to a random earlier node), the empty tree and one node, and check that the degrees sum to n - 1.
Q47N-ary SerialisationMedium

An N-ary tree (a value and a list of children) can be written as text in two ways. Values here are strings with no spaces, and tokens are separated by one space.

  • Counts: pre-order, each node as its value then its number of children: a 2 b 0 c 1 d 0 is a with children b and c, and c has the child d. Read it back with a stack of (node, children still owed).
  • Levels: level-order with a # after each node's children: the root, then for each node taken from the queue its children's values and a #. Read it back with a queue.

Write both writers and readers, then:

  1. Round-trip 300 seeded random N-ary trees of 0 to 40 nodes with up to 5 children per node, a single node and a root with 1,000 children.
  2. Count the tokens of both formats and compare them with n.
  3. Damaged text raises ValueError in both readers: a missing token, a token left over, a bad count, a value that would be read as the # marker.
  4. The counts format round-trips a chain of 100,000 nodes with no recursion.
Q48Left-Child, Right-SiblingHard

Any N-ary tree can be stored with two references per node, the way a binary tree is: a node's first child becomes its left child and its next sibling becomes its right child. A multilevel linked list in DSA Topic 12 was this shape, child for left and next for right. Write to_binary(nary) and from_binary(root) (both return new trees), then:

  1. Check on 1,000 seeded random N-ary trees (0 to 60 nodes, values 0..n-1) that the round trip gives the same tree, that the N-ary pre-order equals the binary pre-order, and that the N-ary post-order equals the binary in-order. The harness catches every exception and counts it as a failure.
  2. Measure with tracemalloc the bytes per node of a random N-ary tree of 100,000 nodes and of its binary form (the two share the same value objects). The hypothesis: the binary form takes less than half of the bytes, because each children list costs more than two references.
  3. A root with 2,000 children becomes a right path of 2,001 nodes. Convert it and back, find the height with a queue, and show that a recursive height overflows the recursion limit.
Q49Cousins And SiblingsEasy

In a binary tree with distinct values, two nodes are siblings when they have the same parent, and cousins when they are at the same depth (edges from the root, the root being 0) but have different parents. Write:

  1. info_levels(root): a dict from each value to (depth, parent value or None), built level by level with (node, parent value) pairs.
  2. info_dfs(root): the same dict from a depth-first walk that passes the depth and the parent down.
  3. are_cousins(info, x, y) and siblings(root) (a dict from each value to the list of its siblings: none or one in a binary tree).
  4. Check against an oracle that uses the path from the root to each node (len(path) is the depth plus 1, path[-2] is the parent), on every ordered pair of different nodes in all 626 shapes and 200 seeded random trees of 0 to 40 nodes. The harness catches every exception and counts it as a failure.
Q50From Statement To TraversalHard

Many tree problems are solved by choosing the right walk and the right direction for the information. Before any code, name for each statement the walk and which way the information flows:

  1. The sum of the left leaves: leaves that are the left child of their parent.
  2. The tilt: the sum over every node of abs(sum of left subtree - sum of right subtree).
  3. The sum of the deepest leaves: the nodes at the last level.
  4. The values of nodes with no sibling: nodes that are the only child of their parent (the root is not counted).
  5. The largest abs(node value - ancestor value) over every node and each of its ancestors (0 for one node).

Write each with its walk, a brute force that uses a different method (the parents dict, or per-node subtree sums), and a broken variant of the first one. Fuzz all five on all 626 shapes and 300 seeded random trees of 0 to 300 nodes with values from -20 to 20. The harness catches every exception and counts it as a failure.

Q51An In-Order IteratorMediumMust Do

Write a class InOrderIterator(root) for a binary tree of TreeNodes (val, left, right; root may be None). The in-order is left subtree, then the node, then the right subtree. The class hands the values out one at a time and never changes the tree:

  • next() returns the next in-order value, and raises StopIteration when none is left.
  • has_next() says whether another value is waiting.
  • The only state is a stack of the nodes still waiting, so memory is O(h), where h is the height (nodes on the longest root-to-leaf path), and next() is O(1) amortised: over a whole walk each node is pushed once and popped once.
  1. Write the class, with counters for pushes, pops and the peak stack size. Check it against a plain in-order list on all 626 shapes with up to seven nodes and on 300 seeded random trees, including the empty tree. After each full walk assert pushes == pops == n and peak <= h, and that one more next() raises StopIteration.
  2. On random_tree(10**5) compare the peak memory (tracemalloc) of building the whole in-order list with the peak of walking it through the iterator while only summing the values.
  3. Time three ways to walk every value: the iterator, list of a plain stack walk, and a recursive generator that uses yield from. Use left paths of 200, 400 and 800 nodes and the complete tree of 2^17 - 1 nodes. DSA Topic 8 measured what yield from costs on nested lists: each value is passed up through one generator per level. Print the growth per doubling and a verdict only where the ratio is 2x or more.
  4. Use two iterators in step to decide whether two trees have the same in-order sequence, stopping at the first difference. Count the pairs pulled.

State time and space.

Q52The File System As A TreeMediumMust Do

A file system is an N-ary tree. A folder is a node with a list of children, its entries; a file is a leaf with a size. Use NNode(val, children), a value and a list of child nodes in order, and store val = (name, size), where size is an int for a file and None for a folder (an empty folder is still a folder). The root is a folder named "". Everything lives in memory, so no real disk is touched (DSA Topic 8 walked a real folder with os.scandir).

Write build_fs(lines), where each line is "path size" such as "docs/a.txt 120": the path has /-separated names, the last is a file and every earlier name is a folder that is created if missing. Keep a dict from the full path string to its node (DSA Topic 7) so a folder is found in O(1). A folder's children stay in a list, sorted by name once the build is done, so the order is fixed. A path that is used both as a file and as a folder raises ValueError. (A dict of children per node, keyed by name, would be a trie: DSA Topic 16 names it, and it is not used here.)

  1. Write build_fs, then these queries, each over the tree:
    • folder_totals(root): the total size under every folder, in pre-order, as (path, total) pairs; the root's path is "". Compute it in post-order, adding the children's totals.
    • listing(root): an indented outline in pre-order, two spaces per level, a file written as name (size), a folder as name/.
    • deepest_path(root): the full path of a deepest file (most names in the path); on a tie, the first in sorted path order.
    • files_ending(root, ext): every file path whose name ends with ext, sorted.
    • folders_per_depth(root): how many folders sit at each depth (the root is depth 0), by a layer-by-layer walk.
  2. Print the listing and the answers for one small seeded file system.
  3. Check every query against plain computations on the flat list of lines on 300 seeded file systems of 0 to 40 files (including no files at all).

State time and space, with h the nesting depth of the folders.

Q53Morris TraversalHard

An in-order walk needs a stack (or recursion) of up to h entries, h being the height. Morris traversal does it in O(1) extra space by borrowing the tree's own empty right references. At a node cur with a left child, find its in-order predecessor: the rightmost node of the left subtree. If that node's right reference is None, point it at cur (a thread) and go left. If it already points at cur, you have come back along the thread: remove it, visit cur and go right. A node with no left child is visited at once, and you go right (which may follow a thread).

  1. Write morris_inorder(root), counting every thread written or removed (link writes) and every step down a predecessor chain (predecessor steps). Check on all 626 shapes with up to seven nodes and 300 seeded random trees (empty tree included) that the values equal a plain in-order, the tree is restored (to_level equal before and after, check_tree passes) and the link writes are exactly twice the number of nodes that have a left child.
  2. On the complete tree of 2^14 - 1 nodes, on random_tree(10**4) and on a left path of 10^4 nodes, print the counts and assert them against their bounds: predecessor steps at most 2n (each right-reference edge is walked once when threading and once when unthreading), link writes exactly 2 per node with a left child.
  3. Change a few lines to get a Morris pre-order (visit when the thread is made, not removed) and check it against a plain pre-order.
  4. Time Morris against a stack-based in-order on the complete tree of 2^17 - 1 nodes and print the ratio only.
  5. Stop the walk after its first visit and show that the tree is left broken (check_tree raises): when anything else might read the tree during the walk, do not use Morris.

State time and space.

Q54Recursion Or A Stack, MeasuredMediumMust Do

Four ways to produce the in-order values (left subtree, node, right subtree) of a binary tree of TreeNodes (val, left, right) are on the table: a plain recursive function that appends to a list; a loop with an explicit stack of nodes; a recursive generator that uses yield from; and Morris traversal (it threads the tree's empty right references and restores them, using O(1) extra space). A tree's height is the number of nodes on its longest root-to-leaf path, and a recursive walk keeps about that many frames open, while sys.getrecursionlimit() (1,000 by default) caps the frames.

The rule for every comparison here: a time verdict only when the measured ratio is 2x or more. Under 2x print no verdict: within 2x. A ratio that sat near 1.5x when this was planned is printed as a ratio only.

  1. Write the four walkers. Check that all four agree with each other on all 626 shapes with up to seven nodes and on 200 seeded random trees (empty tree included).
  2. Time the four on the complete tree of 2^17 - 1 nodes (best of 3, tree built outside the timer). Print milliseconds and the ratio to the recursion for each, as a ratio only.
  3. Time the recursive walk, the stack and the generator on a left path of 800 nodes (the recursion fits) and print the verdict of generator against stack by the rule.
  4. Run the recursion and the stack on a left path of 10^5 nodes: catch the recursion's RecursionError and print only its type name; the stack must finish.
  5. End with one line built from the computed verdicts that says when to choose which.

State time and space.

Q55Immutable Trees As TuplesHard

A binary tree does not need a class. Nested tuples (val, left, right), with None for an empty child, are hashable (a tree can be a dict key or a set member) and immutable (t[1] = x raises TypeError). Python has no tree type, so this is the nearest thing to a built-in one.

  1. Write to_tuple(root) (nodes to tuples) and from_tuple(t) (tuples to fresh nodes). Check the round trip on all 626 shapes with up to seven nodes and on 300 seeded random trees (empty tree included), and that all 626 tuples are distinct as set members.
  2. Immutability means no in-place change. Write set_value(t, path, new), where path is a string of "L" and "R" steps from the root ("" is the root itself) and the result is a new tree with that one value replaced. Only the tuples on the way from the root to that node are rebuilt (path copying); every other subtree is shared with the old tree. Raise ValueError if the path leaves the tree (including any path in the empty tree). Count the new tuples built, assert it is len(path) + 1, and print old and new trees side by side to show the old one still works. DSA Topic 12 shared list tails the same way.
  3. A json round trip turns tuples into lists. Show it, and write the reader that converts the lists back so the result equals the original tuple tree.
  4. Time a recursive sum over random_tree(10**5) as nodes and as tuples (best of 3, both built outside the timer) and print the ratio only.

State time and space.

Q56Full, Perfect And CompleteMedium

Three words describe a binary tree's shape, and they are easy to mix up. Take the empty tree to satisfy all three (nothing breaks the rule).

  • Full: every node has 0 or 2 children.
  • Perfect: full, and every leaf is at the same depth.
  • Complete: every level is full except possibly the last, and the last level fills from the left.
  1. Write is_full, is_perfect and is_complete for a tree of TreeNodes. Test completeness in level-order: once an empty child has been seen, no real node may follow.
  2. Enumerate every shape with 0 to 9 nodes (6,918 shapes) and print, per node count n, how many are full, perfect and complete.
  3. Check by independent oracles: complete means the shape equals the one from_level(list(range(1, n + 1))) builds; perfect means the same for n = 2^k - 1 and false otherwise; full is tested by walking every node with a stack. Assert the patterns: full shapes exist only for odd n (plus the empty tree at n = 0), perfect shapes only for n = 2^k - 1, exactly one each, and there is exactly one complete shape for every n.
  4. Check that from_level(list(range(1, n + 1))) is complete for every n from 0 to 200, and show one tree that is not complete.

A complete tree is the shape a heap stores in an array (DSA Topic 15, named only; no index arithmetic here).

State time and space.

Q57Flattening A Tree Into A ListHard

Rearrange a binary tree of TreeNodes (val, left, right) in place into a path that goes right: every left becomes None, and following right from the root visits the nodes in the tree's pre-order (node, left subtree, right subtree). The function changes the tree in place, creates no node, and returns the root (None for the empty tree). DSA Topic 12 flattened a multilevel list depth first; this is the same idea on a binary tree.

  1. flatten_rec(root): a recursive post-order in which each call flattens both subtrees and returns the tail (last node) of its flattened result, so the left chain can be spliced between the node and the flattened right subtree.
  2. flatten_stack(root): an explicit stack of nodes still to place, pushing the right child, then the left; each popped node is linked after the previous one.
  3. flatten_o1(root): O(1) extra space. At a node with a left child, hang the node's right subtree after the left subtree's rightmost node, move the left subtree to the right and set left to None, then step right. This is the threading idea of Morris traversal, without the undo.
  4. Check each on all 626 shapes with up to seven nodes and 300 seeded random trees (empty tree included): the set of node identities is the same before and after, the values along right equal the original pre-order, no node has a left child and the tree still passes check_tree. Run the two iterative versions on a left path of 10^5 and show the recursive one raise RecursionError on a path of 2,000.

State time and space.

Q58Connecting Each LevelHard

Give every node a next reference to the node on its right in the same level, None for the last node of a level. Use NextNode(val, left, right, next); the three functions below change the tree in place (they set next) and return the root.

  1. connect_queue(root): a layer-by-layer walk with a queue. Record the size of the widest level: the space is O(w).
  2. connect_perfect(root): for a perfect tree (full, with all leaves at one depth) in O(1) space. Walk each level along the next references already set and link the children below: node.left.next = node.right, and node.right.next = node.next.left when node.next exists.
  3. connect_any(root): any shape in O(1) extra space. Walk a level along its next references and link the level below with a dummy head (DSA Topic 12): the dummy's next ends up as the first node of the next level.
  4. Check against level lists: build the expected levels by a layer walk first, then every node's next must be exactly the following node of its level (the same object) and the last must be None. Use all 626 shapes with up to seven nodes (copied into NextNodes) and 300 seeded random trees (empty tree included); use the perfect trees for connect_perfect.
  5. Find by search the smallest shape on which connect_perfect fails, and print what it does there.

State time and space.

Q59Vertical OrderHard

Put the root in column 0, a left child one column to the left of its parent (column - 1) and a right child one column to the right (column + 1). Row is the depth, the root being row 0. The vertical order lists the columns from left to right, and within a column the nodes from top to bottom; nodes in the same row and the same column are listed by value, smaller first. That last rule is needed: without it the answer depends on the order the nodes happen to be visited in.

Write vertical_order(root) for a binary tree of TreeNodes: it returns a list of lists of values, one per non-empty column, and never changes the tree. The empty tree gives [].

  1. Collect (column, row, value) for every node in one walk with an explicit stack, then sort the triples (DSA Topic 9's tuple keys) and group by column. State why the cost is O(n log n).
  2. Write a brute force from the definition: list every node's root-to-node path as a string of "L" and "R", take the column as R count minus L count and the row as the path length, and order the list by the definition. Check both on all 626 shapes with up to seven nodes, built with seeded values from 0 to 5 (so ties are common), and on 300 seeded random trees (empty tree included).
  3. Grouping nodes by the order they are visited, with no sort, gives different answers. Pre-order can list a deeper node of a column before a shallower one, which breaks the top-to-bottom rule, while level-order keeps it. Find by search the smallest shape where the two disagree and print both beside the rule's answer. Then, separately, find the smallest shape (with values reversed from the pre-order labels) where two nodes share a row and a column and the value rule changes the left-to-right order that level-order gives.

State time and space.

Q60The Boundary Of A TreeHard

The boundary of a binary tree of TreeNodes (val, left, right; values distinct) is the list of values met walking its outline anticlockwise from the root, with no node listed twice:

  • the root;
  • the left boundary, top-down: start at the root's left child and keep going to the left child, or to the right child when there is no left child, stopping at a leaf; the leaf itself is not included here;
  • every leaf, left to right (a leaf has no children; a node with one child is not a leaf), the root excluded when it is the only node;
  • the right boundary, bottom-up: start at the root's right child and keep going to the right child, or to the left child when there is no right child, stopping at a leaf; the leaf is not included here, and the nodes are listed from the bottom up.

The empty tree gives [], a single node gives just the root. If the root has no left subtree, the left boundary is empty (the right side is not borrowed to fill it).

  1. Write boundary(root) from three walks (a loop down each side and a stack walk for the leaves). It never changes the tree. State why it is O(n) time and what the extra space is.
  2. Write a brute force from the definition: list every node's root-to-node path as a string of "L" and "R", mark a node as on the left boundary when its path starts with "L" and every later step is "L" or an "R" taken where the node above has no left child, and mirror that for the right; then order the pieces. Check both on all 626 shapes with up to seven nodes, 300 seeded random trees (empty tree included), and the edge cases: one node, a left path, a right path, a root with one child and a root whose only leaf is on one side.
  3. Show the common bug: when the root has no left child, start the left boundary down the root's right child anyway, so the right side is listed twice. Find the smallest shape where it gives a wrong list and print it beside the truth.
  4. Run boundary on a left path and a random tree of 10^5 nodes to show it needs no recursion.
Q61Duplicate SubtreesHardMust Do

Write duplicate_subtrees(root) for a binary tree of TreeNodes (val, left, right; values are ints; root may be None). Two subtrees are the same when both are empty, or both are non-empty with equal values, the same left subtrees and the same right subtrees. A duplicate subtree is a subtree that is the same as at least one other subtree of the tree (they are different nodes). Report each one once, as the marker serialisation of its root: the pre-order values with # for every empty child, joined by commas (a single node 3 is 3,#,#). Return those strings as a sorted list. The function does not change the tree, and an empty tree or a single node gives []. A subtree inside a duplicate subtree can be a duplicate too, and is reported on its own.

  1. Key every subtree in post-order (children first) and count the keys in a dict. First build the key as a string (left key,val,right key), and count the characters of every key built. On a path of n nodes (each node the left child of the one before, values 1..n) for n = 200, 400 and 800 the key lengths add up to O(n^2): print the totals and the growth per doubling.
  2. Replace the string key by a number for each distinct (left number, val, right number) tuple, looked up in a dict. Every key now has 3 fields whatever the subtree size, so the work is O(n).
  3. Time both on a path of 800 nodes and on a seeded random tree of 800 nodes (min of 3 runs each) and give a verdict only when the ratio is 2x or more.
  4. Check both against a brute force that compares every pair of subtrees with the same-tree rule, on every shape with up to 6 nodes and every assignment of values 0 and 1 (10,067 trees), plus 200 seeded random trees, and a second pass with values drawn from -11, -1, 0, 1 and 11.

State time and space for each version, with h named.

Q62Is One Tree Inside AnotherHard

Write is_subtree(s, t) that is True when some node of s has a whole subtree equal to t (same shape, same values, down to the leaves). The empty tree counts as inside every tree. Neither tree is changed.

  1. Naive: run a same-tree check from every node of s and count the pairs of nodes compared. Take s as a path of 800 nodes that all hold 1, and t as a path of 400 nodes of 1 whose last node holds 2, so t is not inside and every start point is tried. Print the count beside 800 * 400.
  2. Serialise both with markers (pre-order, # for each empty child) and test in on the strings. Show the trap: 2,#,# is found inside 12,#,#, so a lone node 2 is wrongly "found" inside a lone node 12. Put a comma before every token (,2,#,# against ,12,#,#) and the trap is gone.
  3. Give each distinct subtree a number through one shared dict of (left number, val, right number) and look up t's number among s's numbers.
  4. Check all three against an oracle (any node of s whose to_level equals t's) on every pair of shapes with up to 5 nodes, with seeded values 0 and 1, plus cases where t is cut from s.

State time and space for each.

Q63An Expression TreeMedium

A postfix expression is a list of tokens: ints, and the operator strings "+", "-", "*", "/". Write from_postfix(tokens) that builds an expression tree with a stack of nodes: a number becomes a leaf; an operator pops the right operand first, then the left, and becomes their parent. A token list that is empty, leaves more than one tree on the stack, runs short of operands, or holds any other token raises ValueError.

  1. Print the pre-order, in-order and post-order of the tree for 3 4 + 2 * 10 4 / -: they are the prefix, infix and postfix forms (the same three notations the stack topic compared). The infix form is fully bracketed here, because choosing the fewest brackets was a different question.
  2. Evaluate the tree in post-order with fractions.Fraction, so / stays exact. Division by zero raises ZeroDivisionError.
  3. Fuzz 300 seeded expressions of 1 to 8 operands (digits 0 to 9). The tree's result must equal a direct postfix evaluation with a value stack and a prefix evaluation of the tree's pre-order read backwards, including the cases that divide by zero. The post-order of the tree must equal the tokens. No eval.

State time and space.

Q64Distances In A TreeHard

A binary tree has distinct values; nodes are passed to the functions by reference (target and query nodes are in the tree). The distance between two nodes is the number of edges on the path between them. The depth of a node is its number of edges from the root, and the lowest common ancestor of two nodes is the deepest node that has both in its subtree (a node is in its own subtree).

  1. Write distance(up, p, q) that returns depth(p) + depth(q) - 2 * depth(lca) using a parent dict up (the root maps to None, as in the kit's parents): lift the deeper node until the depths match, then climb both until they meet.
  2. Write k_distance_rec(root, target, k) that returns the sorted values of every node at distance exactly k from target. One recursive call returns the distance from the current node down to the target (or -1 when the target is not below it). A node at distance d above the target contributes itself when d == k, and the nodes k - d - 1 levels down its other child when d < k. A target not in the tree raises ValueError.
  3. Write k_distance_climb(up, target, k) that does the same with the parent dict: collect the nodes k below the target, then climb, using the same rule at every ancestor.
  4. Check against an oracle built from the paths between every pair of nodes (each node's root path from the parent dict; the distance is the two lengths minus twice the common prefix) on every shape with up to 6 nodes and on 40 seeded random trees of up to 40 nodes. Treating the tree as a graph and searching outwards from the target also works, but graph search belongs to DSA Topic 17.

State time and space.

Q65Pruning A TreeMedium

Two functions that remove nodes from a binary tree of TreeNodes. Both change the tree in place and return the new root, which is None when nothing is left: the caller must store the returned root (root = prune(root)), because a root that is removed cannot remove itself.

  1. prune_no_one(root): values are 0 or 1. Remove every subtree that contains no 1 (a node stays when its value is 1 or when anything below it stays).
  2. prune_leaves(root, x): delete every leaf whose value is x, then again for the leaves that this exposes, until no leaf holds x. A leaf is a node with no children. Both are post-order: a call returns the new subtree and the parent stores it.
  3. Show the pre-order mistake: testing "is this a leaf with value x" before the children are pruned misses a parent that becomes a leaf afterwards. Find the smallest failing tree by searching shapes in increasing size and print it beside the wrong and the right result.
  4. Check both against a brute force that deletes one such leaf at a time (using the parent dict) until none is left: on every shape with up to 5 nodes and every 0/1 labelling, then on all 626 shapes with seeded values 0..2 and on 300 seeded random trees. Show that ignoring the returned root leaves a removed root in place.
Q66Merging Two TreesMedium

Overlay two binary trees of TreeNodes, position by position (a position is a path from the root, such as left then right): where both trees have a node, the merged node holds the sum of the two values; where only one has a node, the merged tree has that node's subtree as it is; where neither does, nothing. Empty trees are allowed on either side. Write both versions, and put in each docstring whether it builds a new tree or changes an input:

  1. merge_new(a, b) returns a new tree and changes neither input; no node of either input appears in it.
  2. merge_into(a, b) changes a in place and returns its root (or b when a is empty): it reuses the nodes of both inputs, so the result shares nodes with b. It never changes a value in b.
  3. Write each one recursively and with an explicit stack of pairs.
  4. Show the sharing: after merge_into, change a value in the result at a grafted position and print b changing with it.
  5. Check on every pair of shapes with up to 4 nodes and 4 seeded value draws each (2,116 checks per function) against a dict from path string to value. Verify the result's cells, that the inputs are unchanged where promised, and by node ids (compared, never printed) that merge_new shares no node and merge_into creates none.
Q67Rebuilding Without RecursionHard

A binary tree with distinct values is fixed by its pre-order list and its in-order list (pre-order: node, left, right; in-order: left, node, right). Write build_stack(pre, ino) that rebuilds it with one stack and no dict, in O(n) time, with no recursion. It takes the two lists, returns the root (None for two empty lists), and may assume they are the traversals of one tree with distinct values. The rule: take the pre-order values in turn; each new node is the left child of the node on top of the stack, unless the top equals the next unused in-order value (that top has no more left side). In that case pop while the top equals the next in-order value, moving on through the in-order each time, and attach the new node as the right child of the last node popped. Push every new node.

  1. Write the naive recursive builder with list.index and slices and count the index comparisons (the position found plus 1 per call). Print them for a left path of 800, a right path of 800 and a complete tree of 1,023.
  2. Write the recursive builder with a dict from value to in-order position and index bounds, and the stack builder.
  3. Check both against the original on all 626 shapes and 300 seeded random trees of 0 to 300 nodes with shuffled distinct values.
  4. Rebuild left and right paths of 10^5 nodes with the stack builder and compare traversals. Show the recursive dict builder raising RecursionError on a path of 2,000 (type name only).
Q68How Tall Is A Random TreeMedium

The kit's random_tree(n, rng) puts each new node into a free child slot chosen at random. Height counts nodes here: the empty tree is 0, a single node 1. Measure how tall these trees get, because height decides whether recursion is safe.

  1. Write height_levels(root) that returns the height by walking level by level (read len(frontier) at the start of a level and process that many nodes), so it works at any depth.
  2. For n = 10^3, 10^4 and 10^5 and seeds 0 to 9 (random.Random(seed)), print the minimum and maximum height beside log2(n) and n, and the largest height as a multiple of log2(n). Assert that no tree is shorter than ceil(log2(n + 1)) (the complete tree's height, the shortest possible).
  3. Print, against sys.getrecursionlimit(), whether the tallest random tree is below the limit, and whether a path of 1,000 nodes is.
  4. Check that a complete tree (made from from_level(list(range(1, n + 1)))) has height ceil(log2(n + 1)) for n = 1 to 1,000 against the measured height. Sorted keys inserted into a search tree make a path (DSA Topic 14, named only): the shape sets the depth, not the size.
Q69Trees From Parent ArraysMedium

A tree can be stored as a list parent where parent[i] is the index of node i's parent and -1 marks the root. Write tree_from_parents(parent) that returns the root of an N-ary tree of NNodes (value = the node's index, children in increasing index order), or None for an empty list.

  1. Build in two passes: one makes every node, one appends each node to its parent's children.
  2. Validate before building, and raise ValueError that names the index: a parent index below -1 or at least n is out of range; parent[i] == i is a node that is its own parent; no -1 at all means no root; a second -1 is a second root; and after building, every node must be reachable from the root by a level-order walk, or the first unreached index is named (a cycle, or a second piece).
  3. Compute every node's depth (edges from the root) two ways: by climbing parent links with a dict memo so that each node is climbed once, and by a level-order walk from the root. They must agree.
  4. Fuzz 500 seeded arrays of 0 to 30 nodes (valid ones with the labels shuffled, and valid ones with one entry replaced by a random value) against an oracle that accepts only when there is exactly one root, every index is in range, and each node reaches -1 within n steps of climbing. Union-find keeps a forest in an array like this one (DSA Topic 18, named only).
Q70When Not To Build A TreeMediumMust Do

Python has no tree type, and a tree is often the wrong tool. Compare three jobs, each done with a hand-built tree and with a flat structure, on the same data, and decide each by measurement. The three comparisons:

  1. Membership. A binary tree of TreeNodes (val, left, right) holding 50,000 distinct ints in no useful order (values placed by random_tree): is x in it? The tree walk uses an explicit stack and returns whether it found x and how many nodes it visited. The flat version is a set of the same values. 20 present values are looked up.
  2. Nearest value at or above x (the smallest value that is >= x, or None). The tree walk must look at every node and keep the best candidate, because the values follow no order. The flat version is a sorted list with bisect_left. A binary search tree would bring the tree down to a few steps, but that is DSA Topic 14, named only. 20 queries.
  3. Lookup by path in a folder tree of NNodes (val = the folder's name, children = a list) 4 levels deep, every folder with 12 subfolders (22,620 folders). The tree walk goes down from the root, comparing each folder name with the next part of the path (split on /); the flat version is a dict from the full path string (such as d3/d7/d1/d9) to the node. 2,000 lookups.

For each comparison, check that both versions return the same answers, time each with the min of 3 runs, and give a verdict only when the ratio is 2x or more (otherwise print "no verdict: within 2x"). End with one line built from the three verdicts, and say when a tree is still the right choice.

Q71The Leaf Test That LiesEasy

A leaf is a node whose two children are both None. A node with one child is not a leaf. The empty tree has no leaves and no root-to-leaf paths. Earlier in this topic, minimum depth went wrong because 1 + min(left, right) treated a missing child as a path that ends. Here are three more functions with the same mistake: each one answers at a None child, or at a node that is missing only one child.

  • has_path_sum_at_none(root, target) returns target == 0 when it reaches None. Its job is to report whether some root-to-leaf path adds up to target.
  • count_leaves_or(root) counts the nodes where node.left is None or node.right is None.
  • leaf_paths_at_none(root) appends the current path when it reaches None. Its job is to list every root-to-leaf path once, left to right.
  1. Write each one with its correct version beside it. The correct version tests for a leaf with both children None, and treats the empty tree as having nothing.
  2. Check the six functions against an oracle that walks with a stack and records each leaf it pops. Run them on all 626 shapes with up to seven nodes (values 1..n in pre-order) and on a left path of 6. For the path sum, test every target from 0 to 28. Catch every exception and count it as a failure.
  3. Print the empty-tree answers. Then print the smallest failing tree with two or more nodes, drawn with show(), with the wrong answer beside the truth. Count the failures of each broken function.

State time and space.

Q72The Recursion That Runs OutHardMust Do

A recursive tree function keeps one call open for every node on the path it is following, so it needs h + 1 frames, where h is the height (the number of nodes on the longest root-to-leaf path; the empty tree has height 0). CPython raises RecursionError once about sys.getrecursionlimit() frames are open (1,000 by default). On a random tree h stays small, so every test passes. On a path (each node has one child) h = n. Paths are common in real data: a long chain of replies to replies, a deeply nested folder, or sorted keys inserted one by one into a binary search tree (DSA Topic 14).

Here are four recursive functions over TreeNodes (val, left, right), each with its contract:

  • height_rec(root) returns the height.
  • in_rec(root) returns the in-order values (left subtree, node, right subtree) as a list.
  • deserialise_rec(text) reads the marker format: values in pre-order (node, left subtree, right subtree), # for every empty child, tokens joined by commas. So 1,2,#,#,3,#,# is 1 with children 2 and 3. A tree of n nodes writes 2n + 1 tokens. It returns the root.
  • build_rec(pre, ino) rebuilds a tree with distinct values from its pre-order and in-order lists, using a dict from each value to its in-order index. The first pre-order value is the root, and everything before it in the in-order is its left subtree.
  1. Check that all four agree with iterative oracles on all 626 shapes with up to seven nodes and on 300 seeded random trees of 0 to 300 nodes. Catch every exception and count it as a failure.
  2. Run each one on left paths of 200, 400, 800 and 2,000 nodes. Print ok, or the exception's type name only, beside the height and sys.getrecursionlimit().
  3. Raise the limit once, inside try/finally, to 3,000, and run all four on paths of 2,000 and 4,000. The cliff moves; it does not go away.
  4. Write the fixes, each with an explicit stack:
    • in-order with a stack of the left spine;
    • height with a stack of (node, depth) pairs;
    • a deserialiser that keeps a stack of nodes still waiting for a child;
    • a builder that pushes each new pre-order value as the left child of the stack's top, unless the top's value is the next in-order value. In that case it pops while it is, and attaches the new node as the right child of the last node popped.
  5. Check each fix against its recursive version on the step 1 trees, then run it on left and right paths of 10^5.

State time and space for each, and say what h is for each kind of tree.

Q73The O(n) That Is O(n h)HardMust Do

A walk that touches each node once is O(n). Three walks below look like that and are not, because each one does extra work at every node that grows with the tree. Here h is the height (nodes on the longest root-to-leaf path), and a node's depth counts edges from the root.

  • In-order by concatenation: walk(node) = walk(node.left) + [node.val] + walk(node.right). Every call returns a new list. A value at depth d is copied into the list returned by its own call and by each of its d ancestors' calls: the sum of (depth + 1) over all nodes. The first + also builds a temporary list walk(node.left) + [node.val], which copies the left values and the node once more, adding the sum of (left subtree size + 1). In total that is between 1x and 2x the depth sum: about n log2(n) on a complete tree, and n(n + 1) on a left path. DSA Topic 8 showed the same cost for returned lists on nested data.
  • A yield from generator: yield from gen(node.left); yield node.val; yield from gen(node.right). Each value is handed up through its own generator and one for each level above it: the sum of (depth + 1).
  • Post-order by out.insert(0, val): walk node, right, left with a stack and insert each value at the front, so the list ends in post-order (left, right, node). Each insert shifts every value already in the list: n(n - 1) / 2 shifts on any shape.
  1. Write all three. Add optional counters (off when timing) for the element copies, temporary lists included, the hand-offs between generators, and the shifts. The counting generator may pass values up with an explicit for loop: the hand-offs are the same as with yield from. Assert each counter against its formula, computed separately from the node depths.
  2. Print the counts per value on complete trees of 2^k - 1 nodes for k = 9..12 and on left paths of 100, 200, 400 and 800. Print how each grows when n doubles.
  3. Fix each one: append to one shared list; the stack in-order that keeps only the left spine; append in node, right, left order and reverse once. Check every version against these fixes on all 626 shapes with up to seven nodes and on 200 seeded random trees.
  4. Time each slow version against its fix on its worst input: the path of 800 for the first two, and the complete tree of 2^14 - 1 for the insert. Give a verdict only when the ratio is 2x or more (otherwise print no verdict: within 2x). Build the closing line from the verdicts.

The naive diameter, which recomputes a height at every node, has the same pattern. State time and space for every function.

Q74Changing A Tree While Walking ItHard

Two walks that change the tree they are walking, and how each one goes wrong.

A Morris search that returns early. Morris in-order uses O(1) extra space. At a node with a left child, it finds the rightmost node of the left subtree and points that node's right at the current node (a thread), then goes left. When the walk comes back along a thread, it removes the thread, visits the node and goes right. A full walk removes every thread it made. A search that returns as soon as it sees the target leaves some threads behind.

  1. Write morris_find(root, target) with the early return True. Over all 626 shapes with up to seven nodes and every target value, count the searches that leave the tree damaged. Damage means check_tree (which raises ValueError when a node is reached twice) now raises.
  2. On the smallest damaged tree, run a recursive height with a step budget of 500 calls. The budget raises its own exception; catch it and print the type name. Without the budget the height would never finish.
  3. Fix it by finishing the walk after a hit (keep a flag, return at the end). Check the fix on all shapes and targets: the same answers, to_level unchanged and check_tree passing.

Mirroring a node while it waits on an in-order stack. A student wants the in-order and the mirror image in one pass. They swap node.left and node.right at the moment of the visit, then continue with node = node.right as usual.

  1. Run it with a step budget on all 626 shapes, against the in-order of an untouched copy and a separately mirrored copy. Count the trees where a node was visited twice, where a node was missed, and where the final tree is not the mirror. Print the smallest tree for each problem.
  2. Fix it by changing only nodes the walk will not read again: in a pre-order stack walk, swap a node's children before pushing them. Check the fix against a recursive mirror on all shapes.

Print the rule: finish a walk before you change the shape, or change only the nodes the walk will not come back to. State time and space.

Q75Shared Nodes And CyclesHard

A tree built by hand can break the tree rules. In a real tree every node except the root has exactly one parent, and no path leads back up. Two ways a hand-linked structure goes wrong:

  • A shared node: one node is the child of two parents. A recursive size counts its subtree twice. A recursive mirror swaps its children twice, so that subtree ends up exactly as it was.
  • A cycle: a child reference points back to an ancestor. Every walk then runs forever.
  1. Link by hand a 6-node structure where one 3-node subtree hangs under two parents. Print size beside the number of distinct nodes (an id set, compared and never printed). Mirror it, then print the shared node's children before and after.
  2. Link a 3-node structure whose last node's left points back to the root. Run size and a level-order with a step counter that raises after 10^5 steps, and print the exception's type name.
  3. Show that check_tree (which counts nodes and raises ValueError when a node is reached twice) rejects both structures, and write safe_size that calls it first.
  4. Sharing can also happen between two trees. A "copy" that makes a new root but reuses the old children looks fine, and check_tree passes on each tree. Find the smallest tree, over all 626 shapes with up to seven nodes, where mirroring that copy also changes the original. Print it before and after, and print how many nodes the two trees share.
  5. Check that the kit's builders never share a node. Run check_tree on all 626 shapes, on 300 seeded random trees, on paths of 10^5 in both directions and on the complete tree of 2^17 - 1 nodes. Each count must equal the size the builder was asked for.

DSA Topic 8 found cycles in nested lists with the same id set. State time and space.

Q76Nodes Or EdgesEasy

Tree measures can be counted in nodes or in edges, and mixing the two gives answers that are off by one. This topic counts height in nodes (the empty tree 0, one node 1), and depth and diameter in edges (the root is at depth 0; one node has diameter 0). Other books and judges often count height in edges, which makes one node 0 and the empty tree -1.

  1. Print a table of five measures in both conventions: size (nodes, and edges, which is n - 1 except for the empty tree), height, minimum depth (the shortest root-to-leaf path), diameter, and the level of the deepest node (counting levels from 1, or depth from 0). Use the empty tree, one node, a path of 3 and the complete tree of 7.
  2. Write two diameter functions that are both right but count differently. One counts edges, from node heights: left + right. The other counts nodes on the path, from edge heights (empty -1): left + right + 3. Over all 626 shapes with up to seven nodes, print how often they differ and by how much.
  3. Write the bug that mixes them: an edge-height that returns 0 for None. That is the edge-height a leaf should have, so the function really counts nodes, and the + 2 in left + right + 2 adds two edges that don't exist. Find the smallest shape where it is wrong, with show(), and count its failures.

State time and space.

Q77The Iterative Traversal With A BugHard

Each walk below is a one-line slip in an iterative traversal. Each one passes the trees a student usually tries by hand: the empty tree, one node and a left path of 4.

  • Pre-order with a stack, but the children are pushed with if node.right ...: push then elif node.left ...: push, so a node with two children pushes only one.
  • In-order with a stack of the left spine, but after the visit it sets node = None instead of node = node.right.
  • One-stack post-order that remembers the last visited value (last = top.val) and goes right only when top.right.val != last. It is right whenever values are distinct.
  • Level-order with a plain list and queue.pop(), which takes from the end. The list is a stack, so the walk goes depth first.
  1. Write the four and their one-line fixes. For post-order, the fix remembers the last visited node and compares with is.
  2. Print each broken walk's result on the three hand-picked trees.
  3. Check each against the kit's oracle traversals on every shape with up to seven nodes, in increasing size, labelled 1..n in pre-order. For post-order, also try every labelling with values 0 and 1 on every shape with up to six nodes. Print the smallest failing tree with show() and the wrong order beside the right one, and count the failures.
  4. Check the fixed versions on the same trees, on 200 seeded random trees and on paths of 10^5 in both directions. Catch every exception and count it as a failure.

State time and space for each.

Q78Serialising Without MarkersMedium

The marker format writes a tree's values in pre-order (node, left subtree, right subtree), writes # for every empty child, and joins the tokens with commas. So 1,2,#,#,3,#,# is 1 with children 2 and 3, and the empty tree is #. It reads back in one pass because every token says what it is. A format cannot be read back when two different trees write the same text, or when the reader rejects text its own writer produced. Here are three "shorter" versions a student might try:

  • Leaf markers dropped: a leaf writes only its value, without its two #s. A node with one child still writes # for the missing side.
  • No separator: the same tokens joined with "".
  • The empty tree as "": every other tree is written in the marker format. The reader splits on commas, so "" becomes one token "", which is not a number.
  1. With no markers at all, count how many 4-node shapes write the same text when labelled 1..4 in pre-order.
  2. For the first two, search for two different trees that write the same text. Go in increasing size and stop at the first collision. The leaf-marker search runs over every shape with up to 5 nodes, labelled 1..n in pre-order (the collision depends only on the shape). The no-separator search runs over every shape with up to 3 nodes and every value from -12 to 12. Print both trees with show() and the shared text.
  3. For the third, round-trip all 626 shapes with up to seven nodes through the strict reader, which raises ValueError for a token that is not a number. Count the failures, and print which tree fails.
  4. Fix all three with the full format, markers and separators and # for the empty tree. Show that the colliding pairs now write different texts. Round-trip all 626 shapes and 300 seeded random trees of 0 to 300 nodes with values -12..12, catching every exception as a failure.

State time and space.

Q79The LCA That Assumes Too MuchMedium

The lowest common ancestor (LCA) of nodes p and q is the deepest node that has both of them in its subtree, where a node counts as being in its own subtree. p and q are passed as nodes (identity, not values; matching by value was the trap earlier in this topic). Both functions below are right when their assumptions hold, and wrong when they don't.

  • The one-pass LCA assumes both nodes are in the tree. An empty subtree returns None; a node that is p or q returns itself; otherwise, if both children answered the node is the LCA, else it passes up the one answer. If q is not in the tree, it still returns p, an "ancestor" of a node that does not exist.
  • The parent climb assumes the two nodes are at the same depth. With a parents dict (each node to its parent, the root to None), it moves p and q up together until they meet. If their depths differ they never meet: one reaches None, and parents[None] raises KeyError. It also raises for a node that is not in the dict.
  1. Write both, and fix each one. Write lca_checked(root, p, q) as one post-order pass that returns how many of p and q it found below each node, and answers only when that count reaches 2. It returns None when either node is absent. Write lca_climb to return None for an absent node, lift the deeper node until the depths match, and then climb both together.
  2. Test every pair of nodes, including a node with itself, on every shape with up to six nodes. Also test pairs where q, p or both are a stranger node that is not in the tree. The oracle is the last node shared by the two root paths found through parents, or None if a node is absent. Catch every exception and count it as a failure.
  3. Print a table of failures by case (both present at equal depth, both present at different depths, one absent, both absent) for the four functions. Print the smallest failing case of each broken function with show().

State time and space.

Q80The Balance Check That LiesMedium

A tree is height-balanced when, at every node, the heights of its two subtrees differ by at most 1. Height counts nodes: the empty tree is 0 and one node is 1. The empty tree is balanced. Each check below passes the tests its author wrote, the empty tree, the complete tree of 7, from_level([1, 2, 3, 4]) and the lopsided from_level([1, 2, 3, None, None, 4, None, 5]):

  • Sizes for heights: at every node, compare the two subtrees' node counts and allow a difference of at most 1.
  • Leaves within one level: call the tree balanced when its shallowest and deepest leaves are at most one level apart. It sounds like the same rule, and it is not.
  • One pass that forgets the -1: a helper returns the height, or -1 for "unbalanced below". It checks abs(left - right) > 1 but never checks whether left or right is already -1. A -1 beside a 0 then passes, because abs(-1 - 0) <= 1.
  1. Write the definition as the oracle: a separate height for both subtrees of every node.
  2. Write the three checks and the fixed one-pass check. The fix returns -1 as soon as either child returned -1.
  3. Run all four on the author's tests, then on every shape with up to 8 nodes (2,056 trees) and on 200 seeded random trees of 0 to 200 nodes. Catch every exception and count it as a failure.
  4. For each broken check, count its false "balanced" and false "not balanced" answers. Print the smallest failing shape with show(), the check's answer beside the truth, and the subtree heights at the root.
  5. The leaf rule can also be wrong the other way, on trees larger than the search covers. Build the sparsest balanced tree of height 5, where every node's left subtree is exactly one taller than its right (12 nodes), and run the leaf check and the definition on it.

State time and space, including the oracle's.

Q81Traversals That Do Not MatchHard

A builder that rebuilds a tree from its pre-order and in-order lists (the values are distinct) is easy to write when both lists are right. This question feeds it lists that are not.

  1. Write build_naive(pre, ino): the root is pre[0], k = ino.index(pre[0]), then recurse on (pre[1:k+1], ino[:k]) and (pre[k+1:], ino[k+1:]). Run it on six bad pairs: a pre-order longer than the in-order, an in-order longer than the pre-order, a value missing from the in-order, the traversals of two different trees, and two lists of repeated values ([1, 1] and [5, 5, 5]). For each, print whether it raised ValueError (from list.index) or quietly built a tree, and for a built tree the pair that tree really has, beside the pair that was given. For repeated values, count how many tree shapes fit the pair.
  2. Write build_checked(pre, ino). It raises ValueError if the lengths differ or any value is repeated; it builds with a dict from value to in-order position and index ranges (no slices); it then re-traverses the tree it built, as a postcondition guard on the builder, and raises ValueError naming the first position where its pre-order or in-order differs from the lists it was given. It returns a new tree.
  3. Fuzz 500 seeded corrupted pairs. Take a tree of 0 to 7 nodes (every fifth one a path), write its two lists, then swap two entries, delete one entry or substitute one entry, in either list. Every pair must be rejected with ValueError, or accepted and rebuilt exactly (both traversals of the result equal the input). Check acceptance against a brute force over every shape with that many nodes. Any other exception counts as a failure. Assert that the empty tree, a single node and a path were each hit.

State time and space, with h the height of the tree built.

Q82The Queue That Holds Half The TreeMedium

A common belief says that a level-order walk with a queue uses less memory than a recursive walk. Measure it before believing it. Height here counts nodes (the empty tree has height 0).

  1. Write level_peak(root): a level-order walk that counts the nodes and returns the largest queue length it saw. Write depth_peak(root): a recursive pre-order walk that counts the nodes and returns the deepest nesting of calls on real nodes (this equals the height). Write stack_peak(root): an in-order walk with an explicit stack that returns the largest stack length.
  2. Hypothesis: on the complete tree of 2^17 - 1 nodes the queue reaches about half the nodes (the last level) while the recursion is about 17 deep. Check it, then run the three walks on random_tree(10**5) and on a left path of 800 nodes (plain recursion on 800 is safe).
  3. For each walk on each shape, also measure the tracemalloc peak in bytes of the walk alone (the tree is built before tracing starts, and the walks return only counts).
  4. For each shape, print which is smaller by entries, the queue or the recursion depth, computed from the numbers, and build the closing line from those verdicts.

State the space of each walk in terms of w (the widest level) and h.

Q83State That Leaks Between CallsMedium

A tree function that keeps its running result outside the call works on the first tree and fails on the next. The diameter is the number of edges on the longest path between any two nodes (0 for the empty tree and for one node); a node's height counts nodes.

  1. Write three buggy helpers and run each on two different trees in a row, printing the answer beside the truth:
    • diameter_global, which keeps its best in a module-level variable and never resets it;
    • diameter_no_nonlocal, whose inner function assigns to the outer best without nonlocal (catch the error and print its type name);
    • pre_bad(node, out=[]), a pre-order that collects into a default list (DSA Topic 8 showed the mutable default; here it leaks values from one tree into the next).
  2. Fix each: diameter_pair returns (height, diameter) up the recursion with no outside state; diameter_local keeps its best in the call with nonlocal; pre_fixed(node, out=None) makes a fresh list. Run both fixes on the same two trees in a row.
  3. Check the diameter versions against a brute force (the longest distance over every pair of nodes, found with the parents dict and two climbs) on all 626 shapes of up to 7 nodes in a fixed order, then on 300 seeded random trees of 0 to 30 nodes, without resetting anything between trees. Count how many answers the global version gets wrong, and where the first wrong one is. Any exception counts as a failure.

State time and space, with h the height.

Q84Levels That Bleed TogetherMedium

Grouping a level-order walk into levels (level d is every node at depth d, the root at depth 0) is where students mix levels. Four common bugs:

  1. levels_len_late: pops the first node of the queue and pushes its children, and only then reads len(queue) to decide how many more nodes belong to the level.
  2. levels_counter: stores (node, level) in the queue and raises one level counter once per node popped, then gives each node's children that counter.
  3. levels_marker: puts a None marker after the root, and when it pops a None it saves the level and stops.
  4. right_view_bug: the right side view (the last node of every level), written to take the first node of each level.

Write the four, a correct levels_ok and right_view_ok (len(queue) read once, before the pops), and an oracle that uses recursion with a dict from depth to values. Run every version over all 626 shapes of up to 7 nodes (values 1..n in pre-order). For each bug print how many shapes it fails on and the smallest failing shape in increasing size, as to_level and its picture, with the wrong output beside the right one. Then check the correct versions on all 626 and on 300 seeded random trees of 0 to 60 nodes, counting any exception as a failure.

State time and space, with w the widest level.

Q85The Suite That Catches All Of ItHardMust Do

Write one test suite for any function that takes the root of a binary tree (nodes are TreeNode(val, left, right)), and prove it by planting six bugs it must catch. The suite is run_suite(fn, oracle, promise, any_depth) and returns the set of check names that failed. promise says what fn does to its input: "read-only" (changes nothing and returns a list or a number), "new tree" (returns a new tree sharing no node with the input and changes nothing) or "in place" (changes the input tree itself and returns nothing useful). oracle(root) computes the right answer by a different method, before fn runs. Every tree is built fresh for each run, so one function cannot poison the next check.

  1. The checks, in this order:
    • oracle: shapes: the answer equals the oracle's on every shape of 0 to 7 nodes (626 trees, values 1..n in pre-order).
    • oracle: random: the same on 300 seeded random trees of 0 to 60 nodes.
    • oracle: path 800: the same on a left path and a right path of 800 nodes.
    • any depth: path 10^5: only when any_depth is true, the same on a left path of 10^5 nodes (this trial skips the before-and-after copies of input unchanged, to stay fast).
    • input unchanged: for "read-only" and "new tree", the level-order list (to_level) and the set of node ids are the same before and after the call, and for "new tree" no node of the result is a node of the input. For "in place" the node ids are the same and to_level after the call equals the oracle's answer for the tree before it.
    • tree intact: check_tree (a helper that counts a tree's nodes and raises ValueError if any node is reached twice) still passes on the input after the call: no shared child, no cycle.
    • no exception: fn raised nothing (any Exception counts, RecursionError included).
  2. The six planted bugs, each with its clean partner:
    • a pre-order with an explicit stack that pushes the left child before the right one;
    • a minimum depth (the number of nodes on the shortest root-to-leaf path, 0 for the empty tree; a leaf has no children) that treats a missing child as a path of length 0;
    • a balance check (at every node the two subtrees' heights differ by at most 1) whose helper returns -1 for "unbalanced" but whose caller does not pass a child's -1 up;
    • a recursive in-order that promises to work at any depth, run on a path of 10^5 nodes;
    • an in-place mirror (swap every node's two children) sold as a copy: it swaps in place and returns the same root, though it promises a new tree;
    • a Morris in-order walk (in-order with no stack and no recursion: each node's left subtree's rightmost node temporarily points back to the node, and the walk cuts that link when it returns through it) that stops the first time it finds a link already made, appending the node and leaving the link in place.
  3. Print a table of bug against the checks that caught it, then the clean versions passing. Assert that each bug is caught by the check it was designed for and that no clean version is flagged. Count the empty tree, a single node and the paths among the trials.

State time and space of the suite, with n the nodes of one tree and h its height.

Q86The Tree ToolkitMini-ProjectMust Do

Build a BinaryTree class that wraps a root (TreeNode(val, left, right), values are ints, a tree may be empty) and offers the whole topic as methods. Height counts nodes (the empty tree has height 0); the diameter counts edges; a leaf has no children; balanced means that at every node the two subtrees' heights differ by at most 1. Every method is iterative, so the toolkit works on a path of 10^5 nodes, and no method changes the tree.

  1. Methods and their contracts:
    • BinaryTree.from_level(values) and to_level(): the level-order list with None gaps ([1, 2, 3, None, 4]), trailing Nones cut;
    • size(), height(), leaves() (the number of leaves);
    • pre_order(), in_order(), post_order(), level_order(): iterators of values;
    • mirror(): returns a new BinaryTree, the left-right mirror image;
    • same_as(other): same shape and same values;
    • serialise() and BinaryTree.deserialise(text): pre-order with # for each missing child, comma separated (1,2,#,#,3,#,#; the empty tree is #); deserialise raises ValueError on a bad value, extra tokens or a truncated list;
    • balanced() and diameter(): one pass each, as a post-order with an explicit stack and a dict from node to result;
    • check(): returns the node count, raises ValueError if a node is reached twice.
  2. Fuzz every method against a plain recursive version on all 626 shapes of up to 7 nodes and 300 seeded random trees of 0 to 60 nodes; any exception counts as a failure; also check that the tree is unchanged afterwards. Assert that the empty tree, a single node and a path were each hit.
  3. Run every method once on a path of 10^5 nodes (a recursion would raise RecursionError, so none is used), and print the height beside sys.getrecursionlimit().

State time and space for each method, in comments.

Q87The Tree PrinterMini-Project

Build a small printer for binary trees with int values, in ASCII only.

  1. draw(root): a top-down picture. A node's column is its in-order index (0 for the leftmost node) times a cell width, cell = (digits of the longest value) + 1; its row is 2 * depth. The rows in between carry one / or \ per edge: for a left child at column cl under a parent at column cp, a / at column (cl + cp) // 2, and for a right child a \ at the same midpoint formula. If the picture would be wider than 120 columns (n * cell > 120), return show(root) instead (the sideways picture from the kit).
  2. to_line(root) and from_line(text): a one-line form such as 1(2(,4),3): a value, then, if the node has any child, its left and right forms in parentheses separated by a comma, an empty child written as nothing. The empty tree is "". from_line reads it back with a stack of nodes waiting for a child (no re, no recursion), and raises ValueError naming the character position of a bad character, a stray ) or ,, a second root, a number written twice in one slot, or a missing ).
  3. Check: the one-line form round-trips on all 626 shapes of up to 7 nodes and on 200 seeded random trees of 0 to 40 nodes (values 0 to 120, so some are three digits); every drawn value sits at the column its in-order index gives (checked with an in-order index computed by recursion); the number of / and \ characters equals the number of edges (so no two edges share a cell) and each one sits at its edge's midpoint; every picture is ASCII; and 300 seeded damaged lines (a character deleted or inserted) either parse or raise ValueError, never another exception.

State time and space of each function, with n the nodes and h the height.

Q88The Folder ExplorerMini-ProjectMust Do

Build an in-memory file system on N-ary nodes, with no disk and no os. The node is class FsNode(NNode) (the kit's NNode(val, children)) with three more slots: val is the name, size is an int for a file and None for a folder, total is a file's size or the sum of the file sizes below a folder, and parent is a reference to the containing folder (None for the root). A node is a folder (it has a list of children, sorted by name) or a file (a leaf with an int size). The root is a folder with the empty name. A path is names joined by / without a leading slash; the root's path is "". The total is kept right as a running value. Because every child points up and the parent points down, a removed folder with contents is a reference cycle: CPython frees it when the cycle collector runs, not the moment the last name goes.

  1. Class Explorer, each method's contract:
    • mkdir(path): create every missing folder along the path; an existing folder is left alone; raises ValueError if a name along the path is a file;
    • add_file(path, size): create the file and any missing folders above it; raises ValueError if the path already exists or a name above it is a file;
    • total(path): the total size under the path (a file's own size); ValueError if there is no such path; kept right by climbing the parents when a file is added, removed or moved;
    • remove(path): delete a file or a folder with everything under it; ValueError for a missing path or the root;
    • move(src, dst): cut the node at src from its parent and attach it under the folder dst (the root is ""); ValueError if src or dst is missing or is the root as src, if dst is a file, if dst is src or lies inside src (found by climbing from dst through the parents), or if dst already has a child with that name;
    • listing(): a list of lines in pre-order, children by name, with the ASCII connectors |-- and `-- (the last child), continued by | or four spaces; a file is name (size), a folder name/, the root /;
    • find(suffix): the sorted paths of every file and folder whose own name ends with suffix;
    • largest(k): the k non-root folders with the biggest totals as (path, total), ties by path;
    • path_of(node): the node's path, built by climbing the parents;
    • totals_postorder(): a dict from every folder's path to its total, recomputed from scratch in post-order (the check on the running totals).
  2. Print a small session: build, list, totals, find, largest, one refused move into its own subtree, one move, one remove.
  3. Check every operation against a flat model (a dict from file path to size and a set of folder paths, every answer recomputed by scanning) on 300 seeded operation scripts of 30 operations over a small pool of names, so that collisions, moves into a subtree, removals and empty explorers all happen. After each operation compare whether it was refused, every running total, totals_postorder(), and every few operations the listing, find, largest and every path_of. Any other exception counts as a failure; assert that a move into its own subtree was refused at least once.

State time and space of each method, in comments (d the depth of a path, b the largest number of children of one folder).

Q89The Org ChartMini-Project

Model a company as an N-ary tree: each employee (an int id) has at most one manager, and the CEO has none. Build an OrgChart class on NNode(val, children) from a dict boss that maps each employee to their manager (None for the CEO; an empty dict is an empty company).

  1. OrgChart(boss): raises ValueError unless there is exactly one CEO (or the dict is empty), every manager is an employee, and everyone is reachable from the CEO (no cycles). Children are kept sorted by id.
  2. Methods and contracts:
    • headcount(m): the number of people under manager m, at any depth, not counting m; computed for everyone in one post-order pass and cached until the next reorganisation;
    • chain(e): the chain of command, [e, e's manager, ..., the CEO], by climbing;
    • lowest_common_manager(a, b): the lowest employee who is a or above a, and is b or above b (so a manager of the other is their own answer);
    • level_sizes(): how many employees sit at each depth (the CEO is depth 0), by a layer-by-layer walk;
    • most_reports(): the employee with the most direct reports, the smallest id on a tie (None for an empty company);
    • reorganise(head, new_manager): move the team under head to report to new_manager; ValueError if head is the CEO, either id is unknown, or new_manager is head or inside head's team (a manager may not report to their own report);
    • to_nested() and OrgChart.from_nested(spec): nested tuples (id, [children...]), children by id, and back.
  3. Check every query against a brute force over the flat boss dict (climbing the dict, counting with Counter, no tree) on a seeded company of 2,000 employees and on 150 small companies of 0 to 12 employees (random, a path and a star, every employee and every pair), before and after seeded reorganisations that the brute force refuses or applies by the same rule. Any exception counts as a failure; print the company's height beside sys.getrecursionlimit().

State time and space of each method in comments (n employees, d the depth of an employee, b the most direct reports one manager has).

Q90The Decision TreeMini-Project

A decision tree is a binary tree that asks questions. Build one by hand from TreeNode(val, left, right): an internal node has two children and val = (feature, threshold), meaning "is item[feature] <= threshold?", with yes on the left and no on the right; a leaf has no children and val is a label string. An item is a dict such as {"age": 37, "income": 52, "score": 4}. This question does not learn a tree from data (that is machine learning; a library such as scikit-learn does it and stores a tree like this one).

  1. Write classify(root, item): walk one root-to-leaf path and return the label (ValueError for an empty tree), and rules(root): every leaf as (conditions, label) in pre-order with the left side first, each condition (feature, "<=" or ">", threshold), plus rule_text that turns one into words (if age <= 30 and score > 5 then maybe).
  2. Write leaf_counts(root, data): for a list of items, how many reach each leaf, in the leaf order of rules.
  3. Write prune(root): changes the tree in place. In post-order, a node whose two children are leaves with the same label becomes a leaf with that label; repeat passes until a pass changes nothing. Return the number of nodes collapsed in each pass.
  4. Write dump(root) and load(text): pre-order tokens joined by ;, an internal node as feature<=threshold and a leaf as =label. load uses a stack, and raises ValueError for a bad token, extra tokens or a truncated list.
  5. The empty tree (None) is allowed: dump(None) is "", load("") is None, leaf_counts(None, data) is [], rules(None) is [], and classify raises ValueError.
  6. Check on a seeded data set of 400 items: the hand-built demo tree against a direct if/else function; then 200 seeded trees (the empty tree, a single leaf, a path-shaped chain and random trees of depth up to 5) against an oracle that scans rules and requires exactly one rule to match; the leaf counts add up to the number of items; pruning changes no answer and leaves no collapsible node; and load(dump(t)) is the same tree. Any exception counts as a failure.

State time and space of each function, with h the height and n the nodes.

Q91The Tree CodecMini-Project

Build a tree codec: three ways to write a binary tree as text, behind one interface. Each codec is an object with name, encode(root) -> str and decode(text) -> root, and decode(encode(t)) must rebuild a tree with the same shape and values.

  1. Markers: pre-order, # for every empty child, tokens joined by ,. The empty tree is #.
  2. Level: the level-order list that to_level produces (None written as #), joined by ,. The empty tree is the empty string, and the decoder must read "" as no tokens, not as one empty token.
  3. Json: nested lists [val, left, right] with null for an empty child, through json.dumps and json.loads.

The encoders and decoders of the first two codecs, and the list-building walks of the third, must be iterative (a stack or a queue), so they work at any depth. json itself recurses inside its C code (CPython), so the json codec checks the height first and refuses a tree taller than 1,000 with ValueError.

Malformed input raises ValueError whose message starts with the position of the offending token (or of the item in pre-order for json, or of the character for broken json text): a missing token, an extra token, a token that is not an int, a value with no parent.

Then:

  1. Print the three encodings of one small tree.
  2. Feed nine malformed inputs (three per codec) and print each error.
  3. Round-trip all 626 shapes with 0 to 7 nodes (seeded values from -40 to 40) and 300 seeded random trees of 0 to 300 nodes, on all three codecs. Count exceptions as failures.
  4. Show that json.dumps of 10^5 levels of nested lists raises RecursionError (print the type name only).
  5. Measure the encoded size and the encode-plus-decode time (min of 3) of each codec on a complete tree, a random tree and a path of 32,767 nodes each. Sizes decide the closing line. For the times, print the slowest-to-fastest ratio only, with no time verdict.

State time and space for every method.

Q92The Traversal VisualiserMini-Project

Build a traversal visualiser that prints the frames of each walk in ASCII, for a student to step through by eye.

Use the 7-node tree from_level([10, 20, 30, 40, None, 50, 60, None, 70]), and draw it once with show().

  1. For pre-order with a stack, in-order with a stack of the left spine, one-stack post-order (with the last-visited check) and level-order with a deque, print one frame per visit: the node visited and the values in the stack or queue right after that step (bottom or front first).
  2. For Morris in-order, print a frame each time a thread is made or removed, written x -> y (the predecessor x, the node y it points back to), and each visit.
  3. A Frames object collects the lines and stops keeping them past a frame limit, printing how many it dropped. Give Morris a limit of 12 so the limit shows, and keep the whole output under 60 lines (counted and asserted).
  4. Check every frame sequence: the visit order equals the oracle traversal, each node is pushed once and popped once (both counted beside the event, so pushes == pops == n), and Morris makes and removes exactly one thread per node with a left child and leaves the tree as it found it. Run the same checks, with the frames switched off, on all 626 shapes with 0 to 7 nodes.

State time and space for every function.

Q93The Tournament BracketMini-Project

Build a single-elimination tournament bracket as a binary tree. Players are numbered 1..p. Pad the draw with byes (written 0) up to the next power of two S, and shuffle it with a seeded random.Random. The players and byes are the leaves, in draw order; each match is an internal node whose two children are the matches (or leaves) that feed it.

  1. make_bracket(draw): build the leaves, then pair neighbouring nodes into the next round until one node is left (no index arithmetic beyond pairing a list's neighbours).
  2. play(root, strength): fill every match node with its winner. A match needs both of its winners first, so this is a post-order. A bye loses to anyone, and two byes give a bye. Otherwise the stronger player wins, except that when (a + b) % 5 == 0 the weaker one wins (an upset). Return how many matches had two real players.
  3. rounds(root): every round's matches as (left, right, winner), round 1 first.
  4. route(player): each player's matches up to their loss or the final, by climbing from their leaf through parent references.
  5. meet_round(a, b): the round in which a and b would meet if both kept winning. That is their lowest common ancestor, and since every leaf is at the same depth, the two climbs move together.

Print a 6-player bracket with show(), its rounds, every route and two meeting rounds. Then check everything against a flat simulation on plain lists (one list per round, plus groups of slots merged round by round for the meeting rounds) on 100 seeded draws of 0 to 40 players. Count exceptions as failures, and assert that the draws hit no players, one player, no byes and a bye against a bye.

State time and space for every function.

Q94The Outline NumbererMini-Project

Build an outline numberer. A document outline is an N-ary tree of sections (NNode, whose val is the pair (title, text)) under a hidden root. Its text form has one line per section: two spaces per level, the title, and optionally | followed by the section's own text.

  1. parse(text): read the lines with a stack of open sections (DSA Topic 10). Reject, with ValueError naming the line number, an indented first line, an indent that is not a multiple of 2, a line more than one level deeper than the line before, and a line with no title.
  2. render(root): write the outline back as the same text, in pre-order with an explicit stack.
  3. numbered(root): number the sections 1, 1.1, 1.2.3 in pre-order.
  4. word_totals(root): each section's own word count, and its count including every subsection. Children are added before their parent.
  5. promote(number): move a section, with its subsections, up one level to just after its parent. Its later siblings stay where they are. demote(number): move a section to the end of its previous sibling's children. Both change the tree in place and raise ValueError when the move is impossible (a top-level section, a first child).
  6. contents(root, depth): a table of contents down to a given depth.

Run it on a 9-section outline: print the numbers and word counts, the contents to depth 2, and the text after one demote and one promote. Then show four rejected outlines.

Check it against a flat model that keeps no tree: a list of (level, title, text) rows. That model numbers with one counter per level, totals each row's block of deeper rows directly, promotes by cutting a block, lifting its levels and inserting it after its parent's block, and demotes by sinking a block's levels where it stands. Run 300 seeded outlines of 0 to 25 sections: each must round-trip and match the model's numbers and totals. Then apply 10 random promotes and demotes to each, comparing the text and the totals after every one, and checking that both sides refuse the same moves. Count exceptions as failures, and assert that the run hit an empty outline, a single section and both kinds of refusal.

State time and space for every function.

Q95The Undo TreeMini-Project

Build an undo tree: a text buffer whose history keeps every branch. State 0 is the starting text. Each state other than 0 stores the edit that made it from its parent, an insert ('ins', pos, s) or a delete (stored with the deleted string so it can be undone).

  1. edit(kind, pos, arg) makes a new child of the current state and moves to it. A new edit after an undo starts a new branch; the old redo history stays in the tree. DSA Topic 10's linear undo stack lost it.
  2. undo() moves to the parent and redo() moves to the most recently created child. Each returns False when there is nowhere to go.
  3. jump(target) goes to any state. It undoes up to the lowest common ancestor of the current state and the target (found by depths and parent climbs), then redoes down to the target, and returns (undos, redos).
  4. replay(sid), the oracle: rebuild a state's text from the start by applying every edit on its path from state 0.

A str is immutable, so every edit and every undo builds a new string. Say what that costs.

Show a branch that a linear undo would lose: edit, edit, undo, edit, then jump back to the lost state. Then run 300 seeded scripts of 40 operations (edits, undos, redos, jumps). After every operation, check the current text against replay. Check each jump's (undos, redos) against the depths of the two states and of their deepest common ancestor, found from a set of ancestors. At the end, check that the tree holds one state per edit plus the start, and jump to every state once more. Count exceptions as failures, and assert that the run hit an undo at the start, a redo with no child, a new branch and a jump across branches.

State time and space for every method.

Q96Explaining It ColdInterview

An interviewer says: "Tell me about trees." Give the explanation as nine short points. Back each one with a line or two printed by code you write on the spot, and say each in plain words:

  1. The node and the words: size, height (in nodes), leaves and the depth of a node (in edges), on one small tree drawn with show().
  2. The four orders, and the job each one is for.
  3. Recursion's stack is O(h): a recursive height on a path of 2,000 (print the error's type name only), against a random tree of 10^5 nodes whose height is printed beside sys.getrecursionlimit().
  4. The iterative versions: in-order with an explicit stack on a path of 10^5.
  5. The one-pass measures: diameter and balance returned up in one post-order. Count calls against the naive diameter on a path of 400.
  6. The lowest common ancestor in one recursive pass, checked by climbing parent references.
  7. Writing a tree down with markers and rebuilding it: the string has 2n + 1 tokens.
  8. N-ary trees, and their left-child right-sibling binary form, which has the same pre-order.
  9. Why Python code rarely builds a tree: count the nodes that 20 searches of the random tree visit, against a set.

Close with one sentence on when a tree is the right choice. State time and space for every function.

Q97Diagnosing By ReasoningInterview

An interviewer hands you five tree functions, each with one bug. For each one, predict the smallest input that fails, and why, before running anything. Write the predictions down in the code as data. Then confirm them with a search over every shape in increasing size (every N-ary shape for the fourth).

  1. A zigzag level order that reverses the even levels instead of the odd ones (the root is level 0, and level 1 should read right to left).
  2. A symmetry check whose helper pairs left.left with right.left (and left.right with right.right) instead of crossing over.
  3. A serialiser that writes # for a missing left child but writes nothing for a missing right one.
  4. An N-ary height (in nodes) that returns 1 plus the number of children.
  5. A parent-pointer LCA that, to even out the depths, lifts the shallower node instead of the deeper one (never past the root), then climbs both together.

For each bug, print the prediction beside the size the search found, and the smallest failing input with the wrong and the right answer. Assert that each prediction held. Check each fix against a different oracle on all 626 shapes with 0 to 7 nodes and on every N-ary tree with 1 to 7 nodes: zigzag against levels gathered from a pre-order with depths, symmetry against a mirrored copy (with every value 7 and with values numbered in pre-order), markers by checking that no two shapes of the same size write the same string, the height against counting levels with a queue, and the LCA against an ancestor set. Explain each prediction in a sentence of plain words.

State time and space for every function.

Q98Designing For OperationsInterview

An interviewer gives you three APIs as complexity targets on a binary tree whose shape is fixed. Design each one, say why it meets its target, and check it against brute force.

  1. subtree_size(u) and subtree_sum(u) in O(1) each, after O(n) preparation. (Hint: one post-order can store both facts on every node.)
  2. is_ancestor(u, v) in O(1), where a node counts as its own ancestor. Use entry and exit counters from one walk: u is an ancestor of v exactly when u is entered no later than v and left no earlier.
  3. subtree_sum(u) when node values change through update(u, val). In pre-order, every subtree is one contiguous run that starts at its root's index and is as long as the subtree's size. So a subtree sum is a difference of two prefix sums (DSA Topic 6). Say what an update costs here, and name the structure that would do better.

Print the answers on one small tree. Then check every API against brute force (walk the subtree; climb parents looking for u). Use all 626 shapes with 0 to 7 nodes and 200 seeded random trees of 0 to 300 nodes: every node for sizes and sums, every pair on small trees and 300 random pairs on the others, and 20 updates per tree, each followed by a query. Count exceptions as failures. Finally, on a random tree of 10^4 nodes, count the nodes a brute-force query visits and the prefix entries an update rewrites, and say which design fits which situation.

State time and space for every method.

Q99The Mock InterviewInterview

Mock interview. "Count the nodes of a complete binary tree (every level full except possibly the last, which fills from the left) faster than visiting all n of them."

  1. The idea: walk the leftmost and the rightmost paths from a node. If they have the same length h, the subtree is perfect and holds 2^h - 1 nodes. Otherwise count 1 + count(left) + count(right). Write it, counting calls and path steps beside the events.
  2. Argue the cost in plain words: why only one child at each level can be imperfect, so the cost is O(log^2 n). Then show it: calls and steps on complete trees of 10^3, 10^4, 10^5 and 2^16 - 1 nodes, printed beside log2(n)^2. Check every complete tree with 0 to 600 nodes, asserting the count and that steps stay within 4 h^2.
  3. Follow-up: "What if the tree is not complete?" Measure it rather than guess. Use a left path of 800 (is the count right, and how many steps does it take?) and 300 seeded random trees (how often is the count wrong?).
  4. Follow-up: "How would you know the tree is complete?" Use the level-order rule from earlier in this topic, in one function.
  5. Follow-up: "Why does a heap never need this?" Answer in one line; heaps are DSA Topic 15.

State time and space for every function, best and worst case where the shape changes them.

Q100CapstoneInterviewMust Do

Build a comment-thread engine, the way a forum stores replies to replies.

The data. Comments arrive as records (id, parent, author, score, length) in arrival order. Ids are distinct non-negative ints, the author is a single word with no spaces, and parent is -1 for a post that starts a new thread. The comments form an N-ary forest: each comment's children are its replies, in arrival order. All threads hang under one hidden root with id -1, which is never shown. Each comment node holds its record's fields, a reference to its parent and the list of its replies. The depth of a comment counts edges from its thread's first post, which is at depth 0. Replies are ranked by higher score first, then smaller id.

The contract. Every walk must be iterative (an explicit stack or a list per level), because a reply chain can be thousands deep, far past sys.getrecursionlimit().

  1. ThreadEngine(records): build in one pass with a dict from id to node. Raise ValueError naming the record's index for a duplicate id, or for a reply to a comment that is missing or arrives later.
  2. replies(cid): the ids of the direct replies to cid (-1 gives the threads), ranked.
  3. render(): one line per comment in pre-order, two spaces per depth, id author (score), with replies ranked. collapse(cid) hides everything below cid: its line then ends with [+k hidden], where k is its number of descendants (no suffix when k is 0). collapse(cid, on=False) shows it again.
  4. totals(): for every comment, the number of comments in its subtree (itself included) and their total score, computed children first.
  5. breadcrumb(cid): the ids from the thread's first post down to cid, found by climbing parent references.
  6. split(a, b): where the two conversations split, which is the lowest common ancestor of a and b (a comment counts as its own ancestor). Return None when they are in different threads.
  7. longest_exchange(): the longest path of replies between two comments of the same thread, in edges (the forest's diameter, never through the hidden root); 0 if there is none.
  8. widest_level(): (depth, count) for the depth with the most comments, ties going to the smaller depth; None for an empty forest.
  9. validate(): walk from the hidden root and check that every comment is reached exactly once, that each one's parent reference points to the node that lists it, and that the dict agrees. Return the count, or raise ValueError.
  10. save() and load(text): a child-count pre-order format. The first line is the number of threads, then one line per comment in pre-order: id author score length k, where k is its number of replies. load reads it back with a stack of open comments. Collapse flags are view state and are not saved.
  11. to_binary(): the left-child right-sibling form (left = first reply, right = next sibling; the threads form the top sibling chain), as TreeNodes (binary nodes with val, left, right) holding ids. As an integrity check, its pre-order must equal the forest's pre-order and its in-order the forest's post-order. Rebuilding a binary tree from those two lists (ids are distinct) with a stack must give the same two lists back.

The checks.

  1. Print a 14-comment seeded forest with one subthread collapsed, then the per-thread totals, a breadcrumb, two splits (one across threads), the longest exchange, the widest level and the validation count, and two rejected record lists.
  2. Write an oracle that builds no tree. It keeps the records in a dict and answers by climbing parent ids: it renders by sorting comments on the rank of every comment along their path, totals by scanning every record's path, splits by the common prefix of two paths, and finds the longest exchange over every pair. Fuzz 300 seeded forests (the empty forest, a single comment, a 40-deep reply chain, then 2 to 60 comments) with up to 3 collapsed comments each. Compare every query, and check validate, the save/load round trip and the binary form. Also check that a reply made to a second parent makes validate raise, and that a reply moved before its parent is refused. Count exceptions as failures, and assert that every case was hit.
  3. Run a 5,000-deep reply chain through render, totals, breadcrumb, the longest exchange, validation, save/load and the binary form. Print its depth beside the recursion limit, and build the closing sentence from the computed results.

State the time and space of every method.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session