ma'am audrey's lessons

ITC 120 › Midterm › Trees and BSTs

Trees and BSTs · Lesson 4 of 6

Tree Traversals by Hand

This lesson teaches:Algorithm

Visiting every node of a binary tree, in three different orders.

By the end, you can:

  1. define a traversal and give real-life examples of programs that need one;
  2. write the pre-order, in-order, and post-order of any binary tree;
  3. check your answer with the walk around the tree picture;
  4. 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 nodeno node is skipped
exactly onceno node is done twice, even if we pass by it again
a fixed rulethe same steps at every node, so everyone who follows the rule gets the same answer
visitdo 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:

Phone foldersFilesDCIMDocsFamily treeLolaMamaTitoOnline shopAllGadgetsShoesa root at the top, branches, and leaves
Folders on your phone, a family tree, and the categories of an online shop. Each one has a root, branches, and leaves. (Remember ?)

A program often has to do one job to every node of trees like these. The picture shows four common jobs:

Show a list1042101710881017, 1042, 1088print every patient numberCount3 studentscount every studentSave a copycopiedback up everything insideDeleteall goneremove everything insideEvery job: visit every node, exactly once.
Print every patient number, count every student, back up a folder, or delete a folder. Each job needs a route that reaches every node, once.

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:

Arrayone way forward5829i++Linked listone way forward102030nullcurrent = current.nextBinary treeTWO ways downABC1down2back up3downFinish one side, come back up,then do the other side.
An array (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.

ABC123startend
We pass A three times: on its left side (1), under it between B and C (2), and on its right side (3).

We write A only once, at one of those three passes. Each choice gives a different order, as this table shows:

Write A…OrderResult
before both sides (pass 1)Pre-orderA, B, C
between the sides (pass 2)In-orderB, A, C
after both sides (pass 3)Post-orderB, 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:

1. Any treea node may have 3 or more childrenPXYZwrite P between which two?Pre-order✓ worksIn-order✗ noPost-order✓ works2. Binary treeat most 2 children: a left and a rightABCleftrightPre-order✓ worksIn-order✓ worksPost-order✓ works3. BSTa binary tree, so all three work201030Pre-order✓ worksIn-order✓ worksPost-order✓ worksbonus: in-order = 10, 20, 30
Pre-order and post-order work on any tree. In-order needs exactly one left side and one right side, so it works only on binary trees. A BST is a binary tree, so all three work there too.

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:

OrderTasksWrite the node…
Pre-orderN L Rbefore its left and right subtrees
In-orderL N Rbetween its left and right subtrees
Post-orderL R Nafter 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

DBGEACF
At A, L means "do all of B, D, E, G," not just B.

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

DBGEACF
N = A. L = B, D, E, G (light teal). R = C, F (gold).

B's turn: now B is N

DBGEACF
N = B. L = D (light teal). R = E, G (gold). A waits for B to finish.

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
here now waiting finished

For Tree L, the three answers are listed in this table:

Pre-orderA, B, D, E, G, C, F
In-orderD, B, G, E, A, C, F
Post-orderD, 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 . 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:

ABDEGCF1234567startend
Pre-order: left sides
ABDEGCF1234567startend
In-order: bottoms
ABDEGCF1234567startend
Post-order: right sides

This is only a shortcut for checking. 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 . They write a node each time the route reaches it.

ABC12345startend

✗ 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.

ABDEGCF1234567startend

✗ 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 .

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.

ABDEGCF1234567

✗ 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 .

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 :

402010306050701234567startend
The numbers 1 to 7 land on 10, 20, 30, 40, 50, 60, 70: smallest to largest.

Why? Remember . 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.

OrderAnswerSorted?
Pre-order40, 20, 10, 30, 60, 50, 70no
In-order10, 20, 30, 40, 50, 60, 70yes
Post-order10, 30, 20, 50, 70, 60, 40no

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.

Copy a folder: pre-ordermake the folder, then copy what is insideGrade 2QuizzesExams123Grade 2 comes firstDelete a folder: post-orderempty it first, then remove the folderGrade 2QuizzesExams312Grade 2 comes last
Same folders, two jobs. Copying needs the folder to exist first, so it goes first (pre-order). Deleting needs the folder to be empty first, so it goes last (post-order).

This table lists the three jobs and the order each one needs:

JobOrderWhy
Copy or list a folderPre-ordercreate the folder first, then what is inside
Print patient numbers from smallest to largestIn-ordersorted output from a BST
Delete a folderPost-ordera 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 . Then check with the walk around the tree, and open the answer. The coding task at the end runs in Java.

Tree S1

134678101314
Show the answer
Pre-order8, 3, 1, 6, 4, 7, 10, 14, 13
In-order1, 3, 4, 6, 7, 8, 10, 13, 14
Post-order1, 4, 7, 6, 3, 13, 14, 10, 8

S1 is a BST, so its in-order is sorted.

Practice 1

KPMRQS
Show the answer
Pre-orderM, K, P, Q, R, S
In-orderK, P, M, R, Q, S
Post-orderP, 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

253035405075809095
Show the answer
Pre-order50, 30, 25, 40, 35, 75, 90, 80, 95
In-order25, 30, 35, 40, 50, 75, 80, 90, 95
Post-order25, 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)

481216202428
Show the answer
Pre-order12, 8, 4, 24, 16, 20, 28
In-order4, 8, 12, 16, 20, 24, 28
Post-order4, 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.

JLMNPRT

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.

10203040506070

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 printPushStack after (top first)
4060, then 2020, 60
2030, then 1010, 30, 60
10nothing (a leaf)30, 60
30nothing (a leaf)60
6070, then 5050, 70
50nothing (a leaf)70
70nothing (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.

  1. Which is the best definition of a tree traversal?

  2. Pre-order visits in which order?

  3. Tree L: what is the in-order?

  4. The root is always ___ in pre-order and ___ in post-order.

  5. Which traversal of a BST always gives the values from smallest to largest?

  6. True or false: "When we come back to a node, we write it again."

  7. On the walk around the tree, in-order writes a node when you pass its…

  8. To delete a folder, everything inside must be deleted first. Which order fits?

Score: 0 / 8

Key takeaways

  1. A traversal visits every node exactly once, following a fixed rule. Programs use it to list, count, copy, or delete everything in a tree.
  2. Pre-order N L R, in-order L N R, post-order L R N, at every node.
  3. L and R mean the entire subtree.
  4. In-order on a BST is sorted.
  5. Root: first in pre-order, last in post-order.
  6. To check: walk around the tree. Left side = pre, bottom = in, right side = post.

Next lesson: Recursion and traversal code.

References

  1. Programiz, "Tree Traversal: Inorder, Preorder and Postorder." programiz.com/dsa/tree-traversal
  2. Programiz, "Binary Search Tree (BST)." programiz.com/dsa/binary-search-tree