Use search-tree order for range sums, the kth smallest, in-order iterators, trimming and building a balanced tree from sorted values.
You keep the receipt ids of a payments app in a search tree. Smaller ids sit on the left of each node and larger ids on the right. The app asks the same kind of question all day.
Each question has a slow answer that reads every id. The order of the tree lets you skip most of them.
A shelf holds numbered boxes in order. You look for box 40 by opening the box in the middle. If its number is larger, everything to its right is larger too, so you never look there.
Here is how this maps to a tree. The middle box is the top node, and each half of the shelf is a smaller tree. The order on the shelf is the order of the ids, so a question about a range of numbers is a question about one stretch of shelf.
Open the middle box of a sorted shelf, and half of it is ruled out at once. Each half is a smaller shelf, which is a smaller tree.
A search tree keeps one rule at every node: all ids on the left are smaller, and all ids on the right are larger. We call the walk that takes the left side, then the node, then the right side an in-order walk. Because of the rule, it gives the ids from the smallest to the largest.
A search tree of n ids can be anything from n levels tall, a chain, to about log n levels, balanced. For 100,000 ids that is 100,000 levels or about 17. Every cost in this lesson depends on that height, which we call h.
Step by step: A tree in memory. The animated player loads in your browser.
Predict what happens
Q A search tree holds 8 at the top, 3 and 10 below it, and 1 and 6 below the 3. What does an in-order walk give?
Answer: B
The walk takes the left side, then the node, then the right side. Under 3 that is 1, then 3, then 6. Then comes 8, and then 10. The ids are in increasing order.
We use one tree for most of the examples. The numbers are only ids.
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13An in-order walk gives 1, 3, 4, 6, 7, 8, 10, 13, 14.
Step by step: An in-order walk gives the ids from the smallest to the largest. The animated player loads in your browser.
You want the ids from 6 to 8. A node tells you what to skip.
def range_total(root, low, high):
total = 0
stack = [root] if root else []
while stack:
node = stack.pop()
if node.value < low:
if node.right:
stack.append(node.right)
elif node.value > high:
if node.left:
stack.append(node.left)
else:
total += node.value
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return totalOn the tree above, the range 6 to 8 reads the nodes 8, 10, 3, 6, 7 and 4, which are 6 of the 9. The total is 6 + 7 + 8 = 21. The ids 14 and 13 are skipped because 10 is above the range, and 1 is skipped because 3 is below it.
A tree of 100,000 ids with values up to 10^9 can total 10^14. That is beyond 2,147,483,647, so Java and C++ need a 64-bit integer.
A range total reads the two edges of the range and the ids inside. Below the range, go right. Above the range, go left.
Exercise · Break it: Find the range this total gets wrong. This function adds the ids from low to high, both included, in a search tree. The tree is built by inserting the ids in the order you give. Find ids and a range where it gives the wrong total.
def range_total(root, low, high):
total = 0
stack = [root] if root else []
while stack:
node = stack.pop()
if node.value <= low:
if node.right:
stack.append(node.right)
elif node.value >= high:
if node.left:
stack.append(node.left)
else:
total += node.value
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return totalThe k-th smallest id is the k-th node of an in-order walk, so stop the walk at k. Keep a stack of the nodes whose left side is being explored. Push a node and its whole left edge, take the top, and continue with its right side.
For k = 4 on the tree above, the walk takes 1, 3, 4 and 6, pushes 5 nodes in all, and stops. The answer is 6, and the right side of 8 is never read.
Predict what happens
Q On the tree above, which id does the walk take as the 5th, and how many nodes has it taken before that?
Answer: B
The order is 1, 3, 4, 6, 7, 8, 10, 13, 14. The 5th taken is 7, and 4 nodes were taken before it.
An iterator gives the next id when asked, and answers whether there is one more. It is the same stack, kept between calls. At the start it pushes the left edge of the tree. Each next takes the top, then pushes the left edge of that node's right side.
| Call | Returns | Stack after, from bottom to top |
|---|---|---|
| start | 8, 3, 1 | |
| 1 | 1 | 8, 3 |
| 2 | 3 | 8, 6, 4 |
| 3 | 4 | 8, 6 |
| 4 | 6 | 8, 7 |
| 5 | 7 | 8 |
Each id is pushed once and taken once, so n calls cost n steps in all, and one call costs 1 step on average. The stack holds one path, so the memory is h. Copying the whole tree into a list first would cost n memory before the first call.
An iterator keeps its stack between calls. Each call takes the top, then pushes the left edge of its right side. Every id is pushed once.
Exercise · Predict the output: What do the next calls return?. The stack holds the left edge of the tree 8, 3, 10, 1, 6, 14, 4, 7, 13 (the ids inserted in this order). The code calls next three times and then prints the three ids and the stack from bottom to top. What does it print?
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
def push_left(stack, node):
while node:
stack.append(node)
node = node.left
root = None
for v in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
root = insert(root, v)
stack = []
push_left(stack, root)
taken = []
for _ in range(3):
node = stack.pop()
taken.append(node.value)
push_left(stack, node.right)
print(*taken, "|", *[n.value for n in stack])If every node also knows the size of its subtree, the k-th smallest needs no walk at all. At a node, the left size says how many ids come before it.
On the tree above the left size of 8 is 5. For k = 4 the walk goes left to 3, where the left size is 1, so k becomes 2 and it goes right to 6. The left size of 6 is 1, so k is 1 + 1: the answer is 6, after reading 3 nodes. Each insert must add 1 to the size of every node on its path, which costs one more path.
Exercise · Find the bug: The k that was not reduced enough. Every node keeps `size`, the number of ids in its subtree. This function should return the k-th smallest id by following one path, or -1 when there is none. It returns the wrong id for some k. Which line is wrong?
def kth(node, k):
while node:
left = node.left.size if node.left else 0
if k <= left:
node = node.left
elif k == left + 1:
return node.value
else:
k -= left
node = node.right
return -1Predict what happens
Q A node has a left side of 6 ids. You ask for k = 9. Where does the search go, and what is k next?
Answer: B
The left size is 6, and k = 9 is more than 6 + 1. So the answer is on the right, and k becomes 9 - 6 - 1 = 2.
An export gives the ids sorted: 1, 3, 4, 6, 7, 8, 10, 13, 14. If you insert them one by one, each id is larger than the last, so each goes to the right. The tree is a chain of 9 levels.
Take the middle id as the top instead, and build each half the same way. Here the top is 7, and the tree has 4 levels. The ids in the order the build creates them (preorder) are 7, 3, 1, 4, 6, 10, 8, 13, 14.
For 100,000 sorted ids the chain has 100,000 levels, and the balanced tree about 17. The build costs n steps either way, since each id is placed once.
Step by step: Sorted ids in order make a chain. The animated player loads in your browser.
Step by step: The middle id first keeps the tree short. The animated player loads in your browser.
Sorted ids inserted in order make a chain of nine levels. Taking the middle id as the top, and each half the same way, gives four levels.
Exercise · Put it in order: The middle-first build. Arrange the lines into a function that takes sorted ids and returns the ids in the order a balanced tree creates them: the middle of the range first, then the left half, then the right half.
def middle_first(ids):
out = []
build(ids, 0, len(ids) - 1, out)
return out
def build(ids, low, high, out):
if low > high:
return
mid = (low + high) // 2
out.append(ids[mid])
build(ids, low, mid - 1, out)
build(ids, mid + 1, high, out)
build(ids, low, mid, out)Predict what happens
Q The ids 1, 3, 4, 6, 7, 8, 10, 13 and 14 are inserted into an empty search tree in sorted order. How many levels does the tree have?
Answer: C
Each id is larger than the one before, so each goes to the right of it. The tree is a chain, with one id on each of the 9 levels.
To keep only the ids from 4 to 10, look at the top. If it is below the range, the answer is what its right side becomes. If it is above, the answer is what its left side becomes. Otherwise keep it, and trim both sides.
On the tree above the result has the preorder 8, 6, 4, 7, 10. The node 3 is below the range, so it is replaced by its right side, which holds 6, 4 and 7.
The node 14 is above the range, so it is replaced by its left side. That is 13, which is also above the range and has nothing on its left. So 10 ends with no right child.
A node that is out of range is replaced, not deleted with its whole side. Its other side may hold ids that are still inside.
Two more tasks use the same order. To delete an id, find its node. A leaf is cut off, and a node with one child is replaced by that child.
A node with two children takes the smallest id of its right side, which is the next id in order. To repair a tree where two ids were swapped, walk it in order. The order breaks in one or two places, and the ids at the breaks are the swapped pair. Both are extra practice.
All costs follow the height h. For 100,000 ids, h is about 17 on a balanced tree and 100,000 on a chain.
| Operation | Balanced tree | Chain | What sets the cost |
|---|---|---|---|
| Search for an id | About 17 steps | n | One path from the top |
| Total of a range | About h + ids inside | n | The two edges of the range, and the ids between |
| The k-th smallest, with a stack | About h + k | n | The first descent, then k nodes |
| The k-th smallest, with sizes | About 17 steps | n | One path, using the left sizes |
| Iterator: one next | 1 step on average, h at most | 1 on average, n at most | Each id is pushed and taken once |
| Iterator: memory | h | n | One path on the stack |
| Build balanced from sorted ids | n | n | Each id is placed once |
| Trim to a range | About 2h | n | The left edge and the right edge of the range |
| Delete an id | About 17 steps | n | Finding the node, then the next id in order for two children |
| Walk every id in order | n | n | Each id is taken once |
| Insert, keeping sizes | About 17 steps | n | One path down, and the same path to add 1 |
A chain makes every one of these cost n. That is why the next step after search trees is to keep them balanced, and why sorted input must be built from its middle.
Use the sandbox to see why order matters. An in-order walk is the same walk you use in all five warm-ups.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build the index behind a receipt archive. The lab gives you a RankedTree class. You add ids with insert, and ask it contains, count, kth, count_below and range_total.
The point is that every node keeps the size of its subtree. A new id adds 1 to the size of each node on its path, and a refused id, one that is already there, must add nothing. With the sizes, kth and count_below follow one path. range_total skips whatever is outside its range.
Three things to take care over:
contains first.kth returns -1 when k is below 1 or above the count. range_total returns 0 when low is above high.Each test creates a new, empty tree, calls your methods in order and compares every value they return. 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 the order of a search tree when the question is about a range, a rank or the next id in order. The walk skips what cannot matter, or stops at the answer. For a range the cost is the height plus the ids inside, and for the k-th smallest with a stack it is the height plus k.
Use a loop and a stack for every walk. A search tree can be a chain of 100,000 nodes, and recursion would be 100,000 calls deep.
If the tree is not a search tree, the skip rules are wrong, because a node below the range says nothing about its left side. Use a full walk, or a count that each side returns.
If sorted ids were inserted one by one, the tree is a chain, and every cost above becomes n. Build from the middle, or use a balanced tree. When ranks are asked many times on a changing set, keep the subtree sizes.
def trim(node, low, high):
if node is None or node.value < low or node.value > high:
return None
node.left = trim(node.left, low, high)
node.right = trim(node.right, low, high)
return nodeTake the range 4 to 10 on the tree above. The root 8 is kept, but 3 is below the range, so this code drops 3 and everything under it, including 6, 4 and 7. It gives the preorder 8, 10, and the right answer is 8, 6, 4, 7, 10. Replace a node below the range with the trim of its right side, and a node above with the trim of its left side.
A common trim mistake: returning nothing for a node out of range. That drops its whole side too, which can still hold ids inside the range.
def next_id(stack):
node = stack.pop()
if node.right:
stack.append(node.right)
return node.valueThe stack starts with the left edge of the tree, 8, 3, 1. This pushes the right child but not the left edge below it. On the tree above it gives 1, 3, 6, 7, 8, 10, 14, so 4 and 13 never appear. The in-order answer has 4 and 13 as well.
After taking a node, push the left edge of its right side: the right child, and then every left child below it.
root = None
for value in sorted_ids:
root = insert(root, value)Each id is larger than the one before, so it goes right every time. The 9 ids of the lesson tree make a chain of 9 levels, where the middle-first build has 4. For 100,000 ids it is 100,000 levels against about 17, and every search costs n. Take the middle id as the top, and build each half.
def in_order(node, out):
if node is None:
return
in_order(node.left, out)
out.append(node.value)
in_order(node.right, out)On a chain of 2,000 nodes this fails in Python with a RecursionError, because Python allows about 1,000 nested calls. Use a stack, as in the iterator above, and a chain of 100,000 nodes is no problem.
int total = 0;
total += node.value;Ids of up to 10^9 add up to 10^14 for 100,000 of them, and a 32-bit integer holds only 2,147,483,647. In Java the total wraps round without a warning. Use long in Java and long long in C++.
Explain 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 · Order and ranges
Q1/3 A search tree has 8 at the top, 3 and 10 below it, and 1 and 6 below the 3. What does an in-order walk give?
Answer: B
The walk takes the left side, then the node, then the right side. Everything on the left is smaller, so the ids come out from the smallest to the largest.
Q2/3 In a total of the ids from 6 to 8, the walk reaches a node with id 3. What does it do?
Answer: C
A node below the range cannot have anything inside the range on its left. Its right side may, so the walk continues there.
Q3/3 A tree has 8 at the top, 3 and 10 below it, 1 and 6 below the 3, 14 below the 10, 4 and 7 below the 6, and 13 below the 14. Which nodes does the total of 6 to 8 not read?
Answer: B
The id 10 is above the range, so the walk goes only to its left, which is empty, and the nodes 14 and 13 are skipped. The id 3 is below the range, so its left side, the node 1, is skipped.
Checkpoint · Stopping early
Q1/2 The walk for the k-th smallest id takes nodes in order. When does it stop?
Answer: C
The k-th smallest is the k-th node of an in-order walk. The rest of the tree is never read.
Q2/2 An iterator has the stack 8, 3, 1 from bottom to top, and next is called. It returns 1. What does the stack hold after the next call, which returns 3, if 3 has a right child 6 with a left child 4?
Answer: C
The call takes 3 from the top. Then it pushes the left edge of its right side: 6, and then 4. So the stack holds 8, 6, 4, with 4 on top, and the next id is 4.
Checkpoint · Sizes and building
Q1/2 A node has a left side of 6 ids, and you ask for the 9th smallest id. Where does the search go, and what is k next?
Answer: C
The left side holds 6 ids, and the node is the 7th. The 9th is on the right, and it is the 2nd there, because 9 - 6 - 1 = 2.
Q2/2 The ids 1, 3, 4, 6, 7, 8, 10, 13, 14 are inserted into an empty search tree in this order. How many levels does the tree have, and how many if 7 is inserted first, and then the middle of each half?
Answer: C
Each id is larger than the one before, so each goes right: a chain of 9 levels. Taking the middle id as the top halves the ids at each level, which gives 4 levels.
Checkpoint · Trimming and limits
Q1/3 To trim a tree to the range 4 to 10, the walk reaches a node with id 3. What replaces it?
Answer: B
An id below the range has only smaller ids on its left, so the left side goes. Its right side can hold ids from 4 up, so it is kept and trimmed in its place.
Q2/3 A tree holds 100,000 ids of up to 10^9, and a range covers all of them. What is the largest total, and what does it need?
Answer: C
A 32-bit integer holds up to 2,147,483,647. 100,000 ids of 10^9 add up to 10^14, which needs 64 bits.
Q3/3 A search tree is a chain of 100,000 nodes. Which walk is safe?
Answer: B
A recursive walk is 100,000 calls deep, and Python allows about 1,000. A stack in a loop holds the nodes in memory with no limit on calls.
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.