Interview problems that use a traversal as a faithful copy of a tree: compare, flatten, repair, count and save. The move: walk in a fixed order and mark the empty children.
You work on a layout checker, a call tracer, a directory service and a thread store. The problems on this street come from them. Each one treats a walk of the tree as the tree itself.
Here is the walk each problem uses, and what the sequence gives you.
| Problem | The walk | What the sequence gives |
|---|---|---|
| Subtree of another tree | preorder with null markers, for both trees | whether the small sequence sits inside the big one |
| Flatten a call trace into a chain | preorder | the order in which to relink the nodes |
| Recover a swapped search tree | inorder | the places where the order falls, which name the pair |
| Save and load a reply thread | preorder with null markers | a string that rebuilds the same tree |
A walk with every empty child marked is not a summary. It is the tree in a different form. The one problem that does not read a walk turns the question round: it counts how many different search trees the same keys can form.
Exercise · Predict the output: The saved layout. Node i has its value in values[i] and its children in left[i] and right[i], with -1 for none. The code writes a preorder walk and marks each missing child with #. What does it print?
values = [4, 2, 6, 1]
left = [1, 3, -1, -1]
right = [2, -1, -1, -1]
out = []
stack = [0]
while stack:
i = stack.pop()
if i == -1:
out.append("#")
else:
out.append(str(values[i]))
stack.append(right[i])
stack.append(left[i])
print(" ".join(out))Pick one walk before you write anything, and mark every child that is missing. The walk is the tree written in a line.
A walk in a fixed order with a marker for every empty child names the exact shape and values of a tree. Two trees are the same exactly when their walks are the same.
The walk then does the work.
The subtree test shows the pay-off. Writing both trees as walks turns a question about shapes into a question about text, and a text search is one call in every language.
The flatten problem uses the same walk in place. Each node's left link is cleared, its right link goes to the next node in preorder, and the old right child must be saved first.
Preorder writes a node, then its left subtree, then its right subtree, with a marker for every missing child.
Exercise · Find the bug: The wrong half of the pair. Two values of a search tree were swapped. This takes its inorder walk and returns the two swapped values, larger first. It is right when the swapped values are far apart but wrong when they are neighbours. Which line is wrong?
def swapped_values(order):
first = -1
second = -1
for i in range(len(order) - 1):
if order[i] > order[i + 1]:
if first == -1:
first = order[i]
second = order[i]
return [first, second]The Academy lessons Tree recursion, Search trees in depth and Build and serialise trees teach the walks and the rebuild. This street changes three things.
The walk must be unambiguous. Without a separator, the preorder of the one-node tree 12 is 12##. It contains 2##, the preorder of the one-node tree 2. A subtree test on those strings says yes, and the right answer is no.
A comma before each token fixes it: ,12,#,# does not contain ,2,#,#.
The walk has a size. A tree of 100,000 nodes writes 200,001 tokens: one for each value and one for each missing child. So the string, the comparison and the rebuild all cost time in proportion to the size of the tree.
The repair uses two falls or one. The inorder walk 1 4 3 2 5 falls twice, and the pair is 4 and 2. The walk 1 3 2 4 falls once, so the pair is 3 and 2, both from the same fall.
Without a separator, the walk of the tree 12 contains the walk of the tree 2, so a subtree test says yes wrongly.
Exercise · Break it: The subtree that is not there. This tests whether the small tree appears as a subtree of the big one, by writing both as preorder strings and searching. Node i has its value in values[i] and its children in left[i] and right[i], with -1 for none. Find an input where it answers wrongly.
def walk(values, left, right):
out = ""
stack = [0]
while stack:
i = stack.pop()
if i == -1:
out += "#"
else:
out += str(values[i])
stack.append(right[i])
stack.append(left[i])
return out
def has_subtree(values, left, right, inner, inner_left, inner_right):
return walk(inner, inner_left, inner_right) in walk(values, left, right)Solve them in this order. The first compares walks, the second relinks along a walk, the third finds the break in a walk, and the last writes a walk and reads it back. One more counts the shapes a walk could name.
Before you code each problem, write which walk you will use and what the empty children look like in it. If you cannot read the tree back from your own walk, the walk is not enough.
Give each problem about 25 minutes. Draw a tree of five nodes, write its walk under it, and rebuild the tree from the walk with the picture covered. Say the walk out loud before you code, as you would to an interviewer.
Test an empty tree, a tree of one node, a tree with only left children, and values with several digits or a negative sign. Most wrong answers come from a walk that two different trees can share.
Checkpoint · Build, save and rewire
Q1/5 A tree has 4 nodes. How many tokens does its preorder walk write, with a marker for every missing child?
Answer: C
Four values and five missing children give nine tokens. A tree of n nodes has n + 1 empty child slots.
Q2/5 Why does a subtree test on preorder strings need a separator before each value?
Answer: B
Without a separator, the walk of the one-node tree 2 is found inside the walk of the one-node tree 12, and the test answers yes wrongly.
Q3/5 The inorder walk of a search tree reads 1, 4, 3, 2, 5. Which values were swapped?
Answer: B
The walk falls twice. The first fall gives the larger value, 4, and the last fall gives the smaller value, 2.
Q4/5 The inorder walk reads 1, 3, 2, 4 and falls once. Which values were swapped?
Answer: A
With neighbours, there is one fall, and both values come from it: 3 on its left and 2 on its right.
Q5/5 A tree of 100,000 nodes is saved as a preorder walk with markers. How many tokens are written?
Answer: C
One token for each of the 100,000 values and one for each of the 100,001 missing children, which is 200,001.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.