ITC 120 › Midterm › Trees and BSTs
Trees and BSTs · Lesson 4 of 6
Tree Traversals by Hand
This lesson teaches:AlgorithmVisiting every node of a binary tree, in three different orders.
By the end, you can:
- define a traversal and give real-life examples of programs that need one;
- write the pre-order, in-order, and post-order of any binary tree;
- check your answer with the walk around the tree picture;
- explain why in-order on a BST gives the values in sorted order.
You need: the Trees lesson, and scratch paper.
Part 1 · The idea
What is a traversal?
Imagine the nurse at your barangay health center has to print a list of every patient in the records. She must not skip anyone, and she must not print anyone twice. If the records are stored in a tree, she needs a plan for moving through it, node by node. That plan is called a traversal.
Tree traversal
A tree traversal is an algorithm (a step-by-step process) for visiting every node of a tree exactly once, following a fixed rule that decides which node comes next.
To visit a node means to do the job on it: print it, count it, copy it, delete it, or anything else the program needs.
Each part of the definition matters. This table explains them one by one:
| The definition says… | In plain words |
|---|---|
| every node | no node is skipped |
| exactly once | no node is done twice, even if we pass by it again |
| a fixed rule | the same steps at every node, so everyone who follows the rule gets the same answer |
| visit | do the job on that node |
In this lesson, we practice traversals by hand, so our "job" at each node is simply to write its value on paper. A real program might print, count, copy, or delete instead. The order of the visits is the same, whatever the job is.
Why does this matter?
Trees are everywhere in IT. You already use these three, even if you never called them trees:
A program often has to do one job to every node of trees like these. The picture shows four common jobs:
That route is a traversal. Later, in Part 5, you will see that some jobs also need a specific order. For example, a folder can be deleted only after everything inside it is gone.
What is new about trees?
You have traversed before, with arrays and linked lists. The picture compares them with a binary tree:
i++) and a linked list (current = current.next) have only one way forward. A binary-tree node can have two ways down.In an array or a linked list, there is only one "next" item, so the route is a straight line. In a binary tree, a node can have two children. So we pick a side, finish it, then go back up to the parent to do its other side. That going back up is the new part, and it is why we need a rule.
When do we write A?
Follow the dashed route in the picture below. Starting at A, we go down to B, back up to A, down to C, and back up to A.
We write A only once, at one of those three passes. Each choice gives a different order, as this table shows:
| Write A… | Order | Result |
|---|---|---|
| before both sides (pass 1) | Pre-order | A, B, C |
| between the sides (pass 2) | In-order | B, A, C |
| after both sides (pass 3) | Post-order | B, C, A |
Pre = before. In = in between. Post = after.
Which trees can we traverse?
In this lesson
We use binary trees, so all three orders work. They do not have to be BSTs.
Extra: what about trees with three or more children?
Extra topic. Trees with more than two children go beyond this course. Open this if you are curious.
The picture checks three kinds of trees:
Why does in-order fail on P? In-order writes the node in between its left and right sides. P has three children, X, Y, and Z, so there is no single "in between" spot: between X and Y, or between Y and Z? Pre-order (P first) and post-order (P last) have no such problem.
Part 2 · The rule
Three tasks at every node
To traverse any binary tree, every node has the same three tasks. They are listed here:
- N write this node.
- L traverse its entire left subtree.
- R traverse its entire right subtree.
The three orders do the same tasks, in a different order:
| Order | Tasks | Write the node… |
|---|---|---|
| Pre-order | N L R | before its left and right subtrees |
| In-order | L N R | between its left and right subtrees |
| Post-order | L R N | after its left and right subtrees |
"Entire" is the key word
L does not mean "move one step left." It means "finish everything on the left side using the same rule, then come back to this node."
Subtrees inside subtrees
From now on, we use this tree, called Tree L. We are at A (orange). Its left subtree is everything under B (light teal), and its right subtree is everything under C (gold):
Tree L
Every subtree has smaller subtrees inside it. Here are the subtrees of Tree L:
- B's subtree: B, D, E, G.
- E's subtree: E, G. It is inside B's subtree.
- D's subtree: just D. A leaf is a subtree too.
- C's subtree: C, F.
When we go down into B's subtree, B becomes the node we are working on: B is now the N. B does its own three tasks on its own, smaller subtree. The two pictures compare A's turn and B's turn:
A's turn: A is N
B's turn: now B is N
When B's whole subtree is finished, we go back up, and A is the N again, ready for its next task. Inside E's subtree, E takes a turn as N, and so on. Every node takes one turn as N, and the rule is the same each time.
Empty sides
If a side is empty (like the left of C, or the right of E), that task is done right away. Skip it and do the node's next task.
Part 3 · Watch it
Step by step
Pick an order. Before each tap, guess: will we write this node now, or go somewhere first? Start with Tree L from Part 2.
Traversal lab
Tap Next step. Orange = the node we are on. Gold = waiting (we must come back). Teal = finished (the node and its whole subtree). #1, #2, … = the order the nodes were written. Below the tree, the task row shows which of the current node's three tasks are done.
Try an example
Color key
For Tree L, the three answers are listed in this table:
| Pre-order | A, B, D, E, G, C, F |
|---|---|
| In-order | D, B, G, E, A, C, F |
| Post-order | D, G, E, B, F, C, A |
Check your answer: walk around the tree
Here is a quick way to check an answer on paper. Draw one route that goes around the outside of the whole tree, starting at the root's left side and hugging every node and edge, like the dashed line below. The route passes every node three times, just like A in Part 1 . Then:
- Pre-order: write each node when the route passes its left side (the first pass).
- In-order: write each node when the route passes under it (the second pass).
- Post-order: write each node when the route passes its right side (the last pass).
The numbers show the order in which the route reaches each spot. Follow the route with your finger and count along:
This is only a shortcut for checking. The three-task rule from Part 2 is what explains why each order works, and it is what the Java code in the next lesson follows.
Part 4 · Watch out
Three common mistakes
These three mistakes come up often on quizzes. For each one, read the situation, look at the picture of the wrong answer, then read the fix.
Mistake 1 · pre-order: writing a node every time you pass it
The situation: a student is asked for the pre-order of the small tree from Part 1 . They write a node each time the route reaches it.
✗ Wrong pre-orderA, B, A, C, A
✓ Right pre-orderA, B, C
What went wrong: following the numbers, the answer is A, B, A, C, A. The tree has 3 nodes, but the answer has 5 entries, because A was written at all three passes (the red ones).
The fix: write each node exactly once, at the one pass your order chooses. Count your answer: 3 nodes, 3 entries. In pre-order, A is written only at pass 1: A, B, C.
Mistake 2 · in-order: going only one step down
The situation: a student is asked for the in-order of Tree L and writes D, B, E, G, A, C, F.
✗ Wrong in-orderD, B, E, G, A, C, F
✓ Right in-orderD, B, G, E, A, C, F
What went wrong: at E, the student treated L as "E has no left child next to it, so write E." But G is in E's left subtree. In-order must finish E's entire left subtree (G) before writing E. Follow the route: it passes under G before it passes under E.
The fix: before writing a node in in-order, ask "is everything on its left already written?" The right answer is D, B, G, E, A, C, F. Compare with the in-order picture .
Mistake 3 · pre-order: reading row by row
The situation: a student is asked for the pre-order of Tree L and reads the tree from the top, row by row.
✗ Wrong pre-orderA, B, C, D, E, F, G
✓ Right pre-orderA, B, D, E, G, C, F
What went wrong: the answer A, B, C, D, E, F, G is a real order called level-order (row by row, top to bottom; you will meet it again in breadth-first search), but it is not one of these three. Pre-order goes deep first: it finishes all of B's side (B, D, E, G) before it ever reaches C.
The fix: follow N L R at every node. The right pre-order is A, B, D, E, G, C, F. Compare with the pre-order picture .
Always true
The root is first in pre-order and last in post-order.
Part 5 · Traversals and BSTs
In-order on a BST is sorted
Here is the starting BST from the earlier lessons, with its in-order numbered under the nodes, using the walk from Part 3 :
Why? Remember the BST rule . Everything left of 40 is smaller and everything right of it is larger. In-order writes the whole left side first (10, 20, 30), then the node (40), then the right side (50, 60, 70): sorted. The same thing happens inside every subtree.
| Order | Answer | Sorted? |
|---|---|---|
| Pre-order | 40, 20, 10, 30, 60, 50, 70 | no |
| In-order | 10, 20, 30, 40, 50, 60, 70 | yes |
| Post-order | 10, 30, 20, 50, 70, 60, 40 | no |
For a BST, in-order always gives the values from smallest to largest. Pre-order and post-order may happen to be sorted, but they do not guarantee it.
Why three orders?
Each order suits a different job. The picture shows two of them on a teacher's "Grade 2" folder: copying it and deleting it.
This table lists the three jobs and the order each one needs:
| Job | Order | Why |
|---|---|---|
| Copy or list a folder | Pre-order | create the folder first, then what is inside |
| Print patient numbers from smallest to largest | In-order | sorted output from a BST |
| Delete a folder | Post-order | a folder can be deleted only when it is empty, so delete the inside first |
Part 6 · Your turn
Practice
Write all three orders for each tree, using the three-task rule . Then check with the walk around the tree, and open the answer. The coding task at the end runs in Java.
Tree S1
Show the answer
| Pre-order | 8, 3, 1, 6, 4, 7, 10, 14, 13 |
|---|---|
| In-order | 1, 3, 4, 6, 7, 8, 10, 13, 14 |
| Post-order | 1, 4, 7, 6, 3, 13, 14, 10, 8 |
S1 is a BST, so its in-order is sorted.
Practice 1
Show the answer
| Pre-order | M, K, P, Q, R, S |
|---|---|
| In-order | K, P, M, R, Q, S |
| Post-order | P, K, R, S, Q, M |
Careful: K has only a right child. This tree is not a BST, so no order has to be sorted.
Practice 2
Show the answer
| Pre-order | 50, 30, 25, 40, 35, 75, 90, 80, 95 |
|---|---|
| In-order | 25, 30, 35, 40, 50, 75, 80, 90, 95 |
| Post-order | 25, 35, 40, 30, 80, 95, 90, 75, 50 |
Careful: 40 has only a left child and 75 has only a right child. This is a BST, so in-order is sorted.
Practice 3 (exam-like)
Show the answer
| Pre-order | 12, 8, 4, 24, 16, 20, 28 |
|---|---|
| In-order | 4, 8, 12, 16, 20, 24, 28 |
| Post-order | 4, 8, 20, 16, 28, 24, 12 |
A BST again: in-order is sorted.
Tap to practice
This tree holds letters, placed like a BST in alphabetical order. Pick an order and tap the nodes in that order. If you miss twice, the next node glows. (Bonus: what do you notice about the in-order?)
Tap the traversal
Pick an order. Then tap the nodes in that order, one at a time.
Show the bonus answer
The in-order is J, L, M, N, P, R, T: alphabetical, because this tree follows the BST rule for letters.
Your coding task: pre-order with a stack
The next lesson writes all three orders in Java with recursion. You can already write pre-order with a tool you know: a stack. The stack holds the nodes that are still waiting for their turn.
Pre-order does N, then L, then R. When you pop a node, print it right away (N). Then its two children wait on the stack. A stack gives back the last item pushed, so push the right child first. Then the left child comes out first: L before R.
Finish preOrder in about 13 lines where it says YOUR CODE. Stack<TreeNode> works like Stack<Integer>, but each item is a node. main builds the starting BST with insert from the BST Insertion lesson. Run it: each printed line must match its comment.
1import java.util.Stack;
2
3public class Main {
4 // Prints the pre-order of the tree.
5 // It uses a stack instead of recursion.
6 static void preOrder(TreeNode root) {
7 // YOUR CODE:
8 // 1. Make a Stack<TreeNode>.
9 // 2. If root is not null, push root. (An empty tree pushes
10 // nothing, so the loop below never runs.)
11 // 3. While the stack is not empty:
12 // a. Pop a node and print its data, then a space. (N)
13 // b. If it has a right child, push the right child.
14 // c. If it has a left child, push the left child.
15 // (Right goes in first, so left comes out first.)
16
17 System.out.println();
18 }
19
20 // Given: insert from the BST Insertion lesson.
21 static TreeNode insert(TreeNode root, int value) {
22 if (root == null) {
23 return new TreeNode(value);
24 }
25 TreeNode current = root;
26 while (true) {
27 if (value == current.data) {
28 return root;
29 } else if (value < current.data) {
30 if (current.left == null) {
31 current.left = new TreeNode(value);
32 return root;
33 }
34 current = current.left;
35 } else {
36 if (current.right == null) {
37 current.right = new TreeNode(value);
38 return root;
39 }
40 current = current.right;
41 }
42 }
43 }
44
45 public static void main(String[] args) {
46 int[] values = {40, 20, 60, 10, 30, 50, 70};
47 TreeNode root = null;
48 for (int i = 0; i < values.length; i++) {
49 root = insert(root, values[i]);
50 }
51 preOrder(root); // expected: 40 20 10 30 60 50 70
52
53 root = insert(root, 45);
54 preOrder(root); // expected: 40 20 10 30 60 50 45 70
55
56 TreeNode chain = null;
57 chain = insert(chain, 10);
58 chain = insert(chain, 20);
59 chain = insert(chain, 30);
60 preOrder(chain); // expected: 10 20 30
61
62 preOrder(null); // expected: (an empty line)
63 }
64}
65
66class TreeNode {
67 int data;
68 TreeNode left;
69 TreeNode right;
70
71 TreeNode(int value) {
72 data = value;
73 left = null;
74 right = null;
75 }
76} ▶ This program runs as is. Try it in the Programiz online compiler: tap Copy, paste it there, and press Run.
Show one possible answer
1static void preOrder(TreeNode root) {
2 Stack<TreeNode> stack = new Stack<>();
3 if (root != null) {
4 stack.push(root);
5 }
6 while (!stack.isEmpty()) {
7 TreeNode node = stack.pop();
8 System.out.print(node.data + " ");
9 if (node.right != null) {
10 stack.push(node.right);
11 }
12 if (node.left != null) {
13 stack.push(node.left);
14 }
15 }
16 System.out.println();
17} Output, one per line: 40 20 10 30 60 50 70, 40 20 10 30 60 50 45 70, 10 20 30, then an empty line.
Here is the starting BST again, one row each time the loop pops a node. The top of the stack is written first:
| Pop and print | Push | Stack after (top first) |
|---|---|---|
| 40 | 60, then 20 | 20, 60 |
| 20 | 30, then 10 | 10, 30, 60 |
| 10 | nothing (a leaf) | 30, 60 |
| 30 | nothing (a leaf) | 60 |
| 60 | 70, then 50 | 50, 70 |
| 50 | nothing (a leaf) | 70 |
| 70 | nothing (a leaf) | empty |
The stack is empty, so the loop stops. The printed order is 40, 20, 10, 30, 60, 50, 70: the same pre-order you get with the walk around the tree. For an empty tree, nothing is pushed, the loop never runs, and the last line prints an empty line.
A common mistake is pushing the left child first. Then the right child comes out first, and the program prints 40 60 70 50 20 30 10: N, R, L instead of N, L, R. The chain 10, 20, 30 still comes out right, because none of its nodes has two children. That is why the tests use more than one tree.
In the next lesson, the recursive preOrder needs no stack of your own. Java keeps one for you: the call stack.
Part 7 · Check yourself
Self-check
For self-study, not for grading. Tap an answer to see if you got it, and read why.
-
Which is the best definition of a tree traversal?
A traversal visits every node, exactly once, in an order decided by a fixed rule. Row by row and smallest to largest are only some possible orders.
-
Pre-order visits in which order?
Pre = before: the node is written before its subtrees (N L R).
-
Tree L: what is the in-order?
L N R at every node: D, B, G, E, A, C, F. (The last option is row by row, which is not one of the three.)
-
The root is always ___ in pre-order and ___ in post-order.
Pre-order writes a node before everything under it, so the root is first. Post-order writes it after everything, so it is last.
-
Which traversal of a BST always gives the values from smallest to largest?
In-order writes the smaller left side, then the node, then the larger right side, at every node.
-
True or false: "When we come back to a node, we write it again."
We may pass a node up to three times, but we write it exactly once. A tree with 7 nodes gives 7 entries.
-
On the walk around the tree, in-order writes a node when you pass its…
Pre-order = left side (the first pass), in-order = bottom (the second pass), post-order = right side (the last pass).
-
To delete a folder, everything inside must be deleted first. Which order fits?
Post-order handles the children (inside) first, then the node (the folder) last.
Score: 0 / 8
Key takeaways
- A traversal visits every node exactly once, following a fixed rule. Programs use it to list, count, copy, or delete everything in a tree.
- Pre-order N L R, in-order L N R, post-order L R N, at every node.
- L and R mean the entire subtree.
- In-order on a BST is sorted.
- Root: first in pre-order, last in post-order.
- To check: walk around the tree. Left side = pre, bottom = in, right side = post.
Next lesson: Recursion and traversal code.
References
- Programiz, "Tree Traversal: Inorder, Preorder and Postorder." programiz.com/dsa/tree-traversal
- Programiz, "Binary Search Tree (BST)." programiz.com/dsa/binary-search-tree