Lesson 2 · Unit 01
Three ways down
Pre-order, in-order and post-order traversal
What you practise
- Pre-, in- and post-order, traced and coded
Try a question from this lesson
Pick one
This prints a node, then walks its left subtree, then its right. In what order are the values printed?
# 1
# / \
# 2 3
# / \
# 4 5
def walk(node):
if node is None:
return
print(node.val)
walk(node.left)
walk(node.right)// 1
// / \
// 2 3
// / \
// 4 5
function walk(node) {
if (node === null) return;
console.log(node.val);
walk(node.left);
walk(node.right);
}// 1
// / \
// 2 3
// / \
// 4 5
function walk(node: Tree): void {
if (node === null) return;
console.log(node.val);
walk(node.left);
walk(node.right);
}Correct answer
1 2 4 5 3
Why
It finishes the whole left side before it ever touches 3: 1, 2, 4, back up for 5, and 3 last. "1 2 3 4 5" would be level by level, which needs a queue. Node-first order is called pre-order.
TypeScript noteTree is the alias Node | null, so the function accepts an empty link. : void says it returns nothing.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Three orders, one line moved
A depth-first walk always goes left before right. The only choice is when to handle the node itself.
Before both subtrees: pre-order. Between them: in-order. After both: post-order. Same function, one line in three possible places.
def walk(node):
if node is None:
return
# pre-order: print here
walk(node.left)
print(node.val) # in-order
walk(node.right)
# post-order: print herefunction walk(node) {
if (node === null) return;
// pre-order: print here
walk(node.left);
console.log(node.val); // in-order
walk(node.right);
// post-order: print here
}function walk(node: Tree): void {
if (node === null) return;
// pre-order: print here
walk(node.left);
console.log(node.val); // in-order
walk(node.right);
// post-order: print here
}TypeScript note: void is the return type of a function that returns nothing. Here the work is the printing, not a result.
9 more exercises in the app
- 2× type the answer
- 1× order the lines
- 3× multiple choice
- 1× match the pairs
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.