Rebuild a tree from two walks, and save a tree as text and load it back.
A notes app keeps its folders in a tree. When you close the app, it must write the tree to a file. When you open it again, it must read the file and draw the same tree. A file holds a line of text, so the tree has to become a line, and the line has to become a tree again.
Listing the folder names in some order is easy. The hard part is the way back. You need enough in the text to rebuild the exact tree.
Your friend draws a branching diagram while you read the names to them over the phone. You read the names in a fixed order: each name, then everything on its left branch, then everything on its right branch. If you read only names, your friend cannot tell where a branch stops.
So wherever a branch ends, you say "nothing". With those words, your friend can always tell which branch comes next.
You read names over the phone while a friend draws. Wherever a branch ends, you say nothing, so your friend knows which branch comes next.
The preorder walk lists a node, then its left subtree, then its right subtree. Here is the lesson's tree, built from the values 8, 3, 10, 1, 6 and 14. Its preorder is 8, 3, 1, 6, 10, 14.
The same preorder fits other trees. The values 1, 2, 3 are the preorder of a chain to the left, of a chain to the right, and of a node with two children. So one walk loses the shape.
You can keep the shape in three ways. Write a mark for every missing child. Keep a second walk, the inorder. Or use a search tree, where the order of the values gives the shape.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q The values 1, 2, 3 are the preorder of three different trees. What is missing from the text 1, 2, 3?
Answer: B
The preorder keeps the order of the nodes, but not where each subtree ends. A chain to the left, a chain to the right and a node with two children all give 1, 2, 3.
Walk in preorder, and write a # for every missing child. The lesson's tree has 6 nodes and 7 missing children, so its text has 13 tokens: 8,3,1,#,#,6,#,#,10,#,14,#,#. A tree of n nodes always has 2n + 1 tokens.
Put commas between the tokens. Without commas, the values 12 and 3 and the values 1 and 23 would both read as 123. An empty tree is the single token #.
Use a stack, not a function that calls itself. Push the right child first, so the left child comes out first. A missing child is pushed as -1 and written as #.
To save a tree, walk it in preorder and write a hash for every missing child. Six nodes and seven marks make thirteen tokens.
Step by step: The preorder walk, the first half of a saved tree. The animated player loads in your browser.
Exercise · Put it in order: Save a tree with marks. A tree is kept as three lists: node 0 is the root, node i holds values[i], and left[i] and right[i] are the nodes below it, or -1 for none. Arrange the lines into a save that writes the preorder with a # for every missing child, with commas and no spaces.
def save(values, left, right):
text = ""
stack = [0] if values else [-1]
while stack:
node = stack.pop()
if node == -1:
text += "#,"
else:
text += str(values[node]) + ","
stack.append(right[node])
stack.append(left[node])
return text[:-1]
text += str(values[node])Predict what happens
Q A tree has 6 nodes. How many tokens does its saved text have, with a # for every missing child?
Answer: C
Every node has two child slots, so 6 nodes have 12 slots. Five of them are filled by nodes, and 7 are empty marks. That is 6 + 7 = 13 tokens, which is 2n + 1.
Read the tokens in order. Keep a stack of the nodes that still wait for a child. The last node on the stack takes the next token, in its left slot first and then in its right slot.
A value makes a new node, which joins the stack. A # fills the slot with nothing. A node whose two slots are filled leaves the stack, and so does each parent that becomes full.
Take the text 8,3,1,#,#,6,#,#,10,#,14,#,#. The token 8 is the root. The tokens 3 and 1 go to the left slots of 8 and 3. The next two marks fill both slots of 1, so 1 leaves the stack.
To load, keep a stack of nodes that wait for a child. The last one gets the next token, left slot first. A full node leaves the stack.
Exercise · Predict the output: How many nodes are waiting?. A load reads the text 5,2,#,#,9,7,#,#,# token by token. Each token fills the next slot of the last waiting node, a value joins the stack as a new node, and a node with both slots filled leaves. The code prints how many nodes are waiting after each token. What does it print?
tokens = "5,2,#,#,9,7,#,#,#".split(",")
waiting = []
sizes = []
for t in tokens:
if waiting:
waiting[-1] += 1
if t != "#":
waiting.append(0)
while waiting and waiting[-1] == 2:
waiting.pop()
sizes.append(len(waiting))
print(*sizes)Predict what happens
Q You are loading the text 8,3,1,#,#,6. The stack holds 8, 3 and 1. The next two tokens are # and #. What happens to the node 1?
Answer: B
Each # fills one slot of the last node on the stack. After two marks the node 1 has both slots filled, so it is finished. The node 3 then gets the next token, 6, in its right slot.
A second walk can replace the marks. Take the preorder 8, 3, 1, 6, 10, 14 and the inorder 1, 3, 6, 8, 10, 14. The first preorder value, 8, is the root. In the inorder walk it is at place 3, counting from 0.
Everything before it in the inorder, 1, 3, 6, is the left part, with 3 values. Everything after it, 10 and 14, is the right part. The next 3 preorder values, 3, 1, 6, belong to the left part, and the rest to the right part.
Do the same for each part. To find the root's place in the inorder fast, build a map from value to place once. Then each split costs O(1), and the whole rebuild costs O(n).
With preorder and inorder, the first preorder value is the root. Its place in the inorder walk splits the left part from the right part.
Step by step: The inorder walk, which splits the tree at the root. The animated player loads in your browser.
Exercise · Find the bug: The right part starts in the wrong place. This function rebuilds a tree from its preorder walk and its inorder walk (distinct values). `position` maps each value to its place in the inorder walk. It collects the post-order of the tree it rebuilds, but on some inputs it gives a wrong result or never ends. Which line is wrong?
def rebuild(preorder, position, pre_start, low, high, out):
if low > high:
return
root = preorder[pre_start]
cut = position[root]
rebuild(preorder, position, pre_start + 1, low, cut - 1, out)
rebuild(preorder, position, pre_start + cut - low, cut + 1, high, out)
out.append(root)Predict what happens
Q The preorder is 8, 3, 1, 6, 10, 14 and the inorder is 1, 3, 6, 8, 10, 14. How many nodes are in the left subtree of 8?
Answer: B
The root 8 is at place 3 in the inorder walk. The 3 values before it, 1, 3 and 6, are the left subtree. The values after it, 10 and 14, are the right subtree.
With postorder and inorder, the root is the last value of the postorder, 8 in 1, 6, 3, 14, 10, 8. The inorder splits the parts in the same way. A preorder with a postorder cannot always rebuild a tree: the values 1, 2 can have 2 as the left child or as the right child.
A search tree needs only its preorder, because its order gives the marks. Keep a stack of the nodes that can still get a right child. A new value pops every smaller value. It is the right child of the last one popped, or the left child of the top.
For 8, 3, 1, 6, 10, 14: the value 6 pops 1 and 3, and becomes the right child of 3. The value 10 pops 6 and 8, and becomes the right child of 8.
Exercise · Break it: Find the walk this rebuild gets wrong. This code rebuilds a search tree from its preorder walk by hanging each value on the one before it, to the left if smaller and to the right if larger. The result is printed as a post-order walk. Find a preorder walk (distinct ids) where it gives a different tree from the correct rebuild.
def from_preorder(values):
root = Node(values[0])
prev = root
for v in values[1:]:
node = Node(v)
if v < prev.value:
prev.left = node
else:
prev.right = node
prev = node
return rootHere are the ways to save and rebuild, for a tree of n nodes. The last two rows show why the details matter.
| Operation | Walk with marks | Two walks, with a map | Search tree, one walk |
|---|---|---|---|
| Text length | 2n + 1 tokens | 2n values in two walks | n values |
| A walk of the whole tree, to save | O(n) | O(n) for each of the two walks | O(n) |
| Load or rebuild | O(n) | O(n) | O(n) |
| Insert a value into the loaded tree | O(height) | O(height) | O(height) |
| Delete a value from the loaded tree | O(height) | O(height) | O(height) |
| Height of the loaded tree, and the stack a walk needs | The shape saved: up to n on a chain | The shape saved | A chain if the values were sorted |
| Rebuild when each root is searched for in the inorder walk | Not needed | O(n^2) | Not needed |
Marks cost the most text and need only one walk. Two walks need no marks, but the values must all be different. A search tree needs the least text, and works only for search trees.
Now watch the walks on a real tree. The sandbox holds the lesson's tree. The walks show the order in which the nodes are visited.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the saver yourself. The lab gives you a TreeSaver class that keeps a search tree and saves and loads it. You write seven methods: add, save, levels, round_trip, size, load and from_walks.
Four things to take care over:
save writes a # for every missing child, with commas and no spaces. An empty tree is #.load reads the tokens with a stack of waiting nodes. Do not call the method for each subtree: a chain of 1,200 nodes is too deep for that.from_walks takes the root from the preorder, splits the inorder at the root, and keeps the parts to do on a stack of tasks.levels writes a # for a missing child of a node in the tree, and drops the marks at the end. An empty tree is the empty text.When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a walk with marks when any tree must become text and come back the same. Use two walks when marks cost too much and the values are all different. Use one walk for a search tree.
The same ideas rebuild trees from a database export, a copied folder, or a message sent between two services.
If the tree never leaves the program, do not save it. Keep the nodes. If you only need to copy a tree, copy the links. Text is for storage and transport, and it costs time to write and read.
One walk loses the shape. The values 1, 2, 3 are the preorder of a chain to the left, a chain to the right, and a node with two children. The three saved texts with marks are different: 1,2,3,#,#,#,#, 1,2,#,#,3,#,# and 1,#,2,#,3,#,#.
save = ",".join(str(v) for v in preorder) # 1,2,3 for all three trees
save = ",".join(preorder_with_marks) # three different textsWithout commas, 12 then 3 and 1 then 23 both read as 123. The comma shows where one value ends and the next one begins.
text = "".join(parts) # "123" for two different chains
text = ",".join(parts) # "12,3" and "1,23"One walk loses the shape. The values one, two, three fit a left chain, a right chain, and a node with two children.
A tree can be a chain of 100,000 nodes. A function that calls itself once for each node nests 100,000 calls deep. In Python the limit is about 1,000 calls, so the call raises a RecursionError. Java and C++ risk a stack overflow.
def read(tokens): # one call for each node: too deep on a chain
node = read(tokens)
# a stack of waiting nodes: no limit on the depth
waiting = [root]To split the parts you need the root's place in the inorder walk. A scan from the start costs the length of the walk each time. On a chain of 100,000 nodes the scans add up to 5,000,050,000 steps. Build a map from value to place once.
cut = inorder.index(root) # O(n) each time: n^2 / 2 steps in all
cut = position[root] # O(1) with a map built onceCutting a list into two new lists for each part copies the values again at every level. On a chain this copies about n^2 values from the two walks together. Pass the start and end places instead, and copy nothing.
left = rebuild(preorder[1:cut + 1], inorder[:cut]) # copies the lists
left = rebuild(pre_start + 1, in_low, cut - 1) # only numbersExplain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · One walk and marks
Q1/3 The preorder walk of a tree is 1, 2, 3. What does that tell you about the tree?
Answer: C
A chain to the left, a chain to the right and a node with two children all have the preorder 1, 2, 3. One walk loses the shape.
Q2/3 You save a tree in preorder and write a # for every missing child. The tree has 9 nodes. How many tokens does the text have?
Answer: C
Each node has two child slots, so 9 nodes have 18 slots. Eight of them hold nodes, and 10 are empty marks. That is 9 + 10 = 19 tokens, which is 2n + 1.
Q3/3 Why must the saved text have commas between the tokens?
Answer: C
The comma shows where one value ends and the next one begins. The marks are the # tokens, not the commas.
Checkpoint · Loading with a stack
Q1/2 You load a tree from text with marks. Which node receives the next token?
Answer: C
The stack holds the nodes with an open slot, from the root down. The last one is the next to get a token, in its left slot first and then in its right slot.
Q2/2 A node on the stack has both of its slots filled. What happens next?
Answer: B
A node has only two slots. When both are filled it is finished. Its parent may then be full too, so the load checks the new last node again.
Checkpoint · Two walks
Q1/3 The preorder is 20, 10, 5, 15, 30 and the inorder is 5, 10, 15, 20, 30. How many nodes are in the left subtree of 20?
Answer: C
The root 20 is at place 3 in the inorder walk. The three values before it, 5, 10 and 15, are the left subtree. Only 30 is on the right.
Q2/3 You have the postorder 5, 15, 10, 30, 20 and the inorder 5, 10, 15, 20, 30. Which value is the root?
Answer: C
In a postorder walk the root comes last, after both subtrees. The inorder walk then splits the other four values into the two parts.
Q3/3 On a chain of 100,000 nodes, you find each root with inorder.index(root). About how many steps do the scans take in all?
Answer: C
Each scan walks past the nodes before the root. On a chain the scans cost 100,000, 99,999 and so on down to 1, which add up to 5,000,050,000. A map from value to place makes each lookup O(1).
Checkpoint · Search trees and depth
Q1/2 A search tree has the preorder 20, 10, 5, 15, 30. You load it with a stack of nodes that can still get a right child. What does the value 15 do?
Answer: C
The value 15 is larger than 5 and 10, so it pops both. It is smaller than 20, so 20 stays. It becomes the right child of 10, the last node popped.
Q2/2 A tree can be a chain of 100,000 nodes. Why is a function that calls itself once for each node a risk?
Answer: B
The Python limit is about 1,000 nested calls, and Java and C++ have a fixed stack too. A loop with a stack of nodes has no such limit.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.