Three problems that look up, add and remove a record in a search tree by links. The move: follow one trail from the top, and change the tree only where the trail ends.
You work on a video app, an ad server and a bank app. Each keeps its ids in a search tree, and each needs one operation on it: find an id, add an id, or remove an id. The three problems on this street are those three operations.
They follow one rule. At a node, a smaller key can only be on the left. A larger key can only be on the right, so one comparison discards a whole side. Repeat it from the top and you walk a single trail of nodes.
| Problem | The trail ends | The work done there |
|---|---|---|
| Look up an id | at the key, or one step before a missing child | report the trail |
| Insert a record | at a missing child | hang a new leaf on it |
| Delete a record | at the key | replace the node, in one of three ways |
Here is the tree the street uses. Its codes are 8, 3, 10, 1, 6, 14, 4, 7 and 13. The top is 8, with 3 on its left and 10 on its right.
The lookup of 7 compares 8, 3, 6 and 7, and stops there. The lookup of 5 compares 8, 3, 6 and 4, and stops at 4, because 4 has no right child.
Exercise · Predict the output: The trail of a missing id. The tree has the codes 8, 3, 10, 1, 6, 14, 4, 7, 13, and node 0 is the top. The loop looks up the key 5. What does it print?
values = [8, 3, 10, 1, 6, 14, 4, 7, 13]
left = [1, 3, -1, -1, 6, 8, -1, -1, -1]
right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
key = 5
node = 0
trail = []
while node != -1:
trail.append(values[node])
if key == values[node]:
break
node = left[node] if key < values[node] else right[node]
print(*trail)Follow the trail with a loop, not with recursion. Keep the current node, and the parent link you came from when you will need it. Then the three problems differ only in what they do at the end.
A lookup reports where the trail ended. An insert connects a new node to the missing child where the trail ended. A delete changes the link that points to the node it found.
Every key that can be in the tree under a node is on the side that the comparison picks. So the trail visits every node that could hold the key, and the only link that must change is at its end.
The insert of 5 follows the trail 8, 3, 6, 4. Node 4 has no right child, so 5 becomes that child. In preorder the tree reads 8, 3, 1, 6, 4, 5, 7, 10, 14, 13. Insert 7 instead, which is already there, and the tree does not change.
An insert follows the lookup trail and hangs the new node on the missing child where the trail ends.
A delete has three cases. A node with no child is removed, and a node with one child lets that child take its place. A node with two children cannot be removed that way, because two children cannot share one link.
For two children, copy the code of the successor into the node. The successor is the smallest code on the right side: from the right child, go left as far as you can. Then remove the successor's old node, which has no left child, so its right child takes its place.
On the street tree, delete 3. Its successor is 4, so 4 replaces 3, and the old node of 4 is removed. The tree reads 8, 4, 1, 6, 7, 10, 14, 13.
Exercise · Find the bug: The successor on the wrong side. This finds the successor of a node: the smallest code on its right side. For the top of the street tree it returns the wrong code. Which line is wrong?
def successor_value(values, left, right, node):
cur = left[node]
while left[cur] != -1:
cur = left[cur]
return values[cur]The Academy lessons Trees and binary search trees and Search trees in depth define the search tree and build the three operations with recursion. This street does not teach them again. It changes three things.
The trail is the answer. The problems ask for the nodes the trail visits, or for the tree after a change, read in preorder. You must also change links only, never rebuild the tree.
The shape sets the cost. Insert the ids 1 to 1,000 in sorted order, and every node has only a right child. A lookup of 1,000 compares 1,000 nodes. Insert the same ids with the middle one first at every level, and no lookup compares more than 10 nodes.
For 100,000 ids the numbers are 100,000 comparisons on a chain and 17 on a balanced tree. A chain of that length also breaks a recursive solution, so write the loop.
Delete has a rule that everyone must share. Two copies of the tree must stay identical, so the two-children case always uses the successor. Delete 8 from the street tree, and 10 takes its place, while the right child of the old 10, which is 14, takes over. The tree reads 10, 3, 1, 6, 4, 7, 14, 13.
Forget to remove the successor's old node, and the code 10 appears twice: 10, 3, 1, 6, 4, 7, 10, 14, 13.
Exercise · Break it: The lookup that does not stop at a match. This lookup follows the trail and records every code. It goes right whenever the key is not smaller. Find a tree and a key where its trail is too long.
def lookup_path(values, left, right, key):
trail = []
node = 0 if values else -1
while node != -1:
trail.append(values[node])
node = left[node] if key < values[node] else right[node]
return trailDeleting a node with two children: copy the successor, then remove its old node, or the code appears twice.
Solve them in this order. The lookup is the trail, the insert adds a leaf at its end, and the delete changes the node it found.
Before you code each problem, write two lines: where does the trail end, and which link changes there? For the delete, write which of the three cases you are in before you touch a link.
Give each problem about 20 minutes. Draw the street tree on paper. Run each operation by hand on two keys, one that is in the tree and one that is not.
Test the cases that hide errors. An empty tree, a key that is the top, a key that is a leaf, and a tree that is a chain of 100,000 nodes. The last one rules out recursion.
When a delete is wrong, print the tree in preorder before and after. Most mistakes are one link that still points to the removed node.
Checkpoint · BST operations
Q1/5 A search tree has the codes 8, 3, 10, 1, 6, 14, 4, 7, 13. You look up 5. Which codes does the trail compare?
Answer: B
The trail goes left at 8, right at 3, left at 6 and right at 4. Node 4 has no right child, so the trail ends there and 5 is not in the tree.
Q2/5 Where does an insert hang the new node?
Answer: B
A lookup for the new code ends at a missing child. Hanging the node there keeps every smaller code on the left and every larger code on the right.
Q3/5 Which node takes the place of a deleted node that has two children?
Answer: C
The successor is the next larger code, so copying it keeps the order. Its old node has no left child, so its right child takes its place.
Q4/5 You insert the ids 1 to 1,000 in sorted order. How many nodes does a lookup of 1,000 compare?
Answer: C
Every new id is larger than all before it, so it becomes the right child of the last node. The tree is a chain, and the trail visits every node.
Q5/5 The delete rule copies the successor's code but forgets to remove the successor's old node. What does the street tree show after deleting 8?
Answer: C
The successor of 8 is 10. Its code moves to the top, and without the removal the old node of 10 stays, so 10 appears twice.
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.