Preorder, inorder and postorder

Video lessonComing soon

1 A tree has no single next node

An array has one natural order: index 0, then 1, then 2. A tree has none. After the root, a walk can go left or right. After a node on the left, it can go deeper or come back up.

Many tree problems still need every node in a fixed order: to print a tree, copy it or add up its values.

The last lesson covered the words and the TreeNode with val, left and right. Our running tree, in level order, is [1, 2, 3, 4, 5, null, 6]:

425136
The running tree. Node 3 has only a right child

The walks here go as deep as they can before they turn back. This is a depth-first search (DFS), and it comes in three orders: preorder, inorder and postorder. Walking level by level is a later lesson.

2 One walk passes each node three times

The whole walk is one short recursive function. On an empty tree, it does nothing. Otherwise, it walks the left subtree and then the right subtree:

walk(node)
    if node is null: return
    // moment 1: just arrived
    walk(node.left)
    // moment 2: back from the left
    walk(node.right)
    // moment 3: back from the right

Around the two calls, there are three places for code. So the walk is at each node three times: when it arrives, when the left call returns, and when the right call returns.

On paper, the walk is a pencil line drawn around the tree. The line starts at the root, goes down the left and hugs the edges all the way round. It passes each node three times: down its left side, underneath it between its two children, and up its right side.

Here is every moment of the walk on our tree, in order. Each node appears exactly three times:

124442555213366631
The walk, one box per moment

A leaf such as 4 appears three times in a row. Both its children are null, so both its calls return at once.

3 Three orders, three moments

The three orders are three ways to pick from that row. Each one writes a node down at one of its three moments and skips the other two:

One walk, three orders
425136
124442555213366631
Preorder, 1st visits: 1 2 4 5 3 6
OrderWrites the nodeOur tree
Preorderon arrival1 2 4 5 3 6
Inorderbetween the subtrees4 2 5 1 3 6
Postorderon leaving4 5 2 6 3 1

The name says where the node goes, and left always comes before right:

  • Preorder reads node, left, right.
  • Inorder reads left, node, right.
  • Postorder reads left, right, node.

The lesson on infix, prefix and postfix read one expression tree in three ways. Those three ways are these three walks:

8-3*2+6/3
(8 − 3) × 2 + 6 / 3
WalkGivesOn this tree
Preorderprefix+ * - 8 3 2 / 6 3
Inorderinfix8 - 3 * 2 + 6 / 3
Postorderpostfix8 3 - 2 * 6 3 / +

Without its brackets, the inorder line reads as a different calculation, worth 4. Only infix needs brackets.

4 Preorder, one call at a time

Preorder writes at moment 1. Here it is as the code runs it. The bold path in the tree is the call stack: the calls that have started and not yet returned.

Preorder on our tree
425136
1
Arrive at 1: write it, go left
preorder(1)top →
call stack

After step 6, the calls for 6, 3 and 1 return one by one, and the walk ends. Two things show in the steps:

  • A subtree is finished before the walk moves right. All of 1's left subtree, 2 4 5, is written before 3.
  • The stack holds one path, never the whole tree. It holds at most three calls here, one per level.

Inorder and postorder make the same calls in the same order. Only the write moves:

  • Inorder writes a node once its whole left subtree is written. So 1 waits for 4, 2 and 5. In a drawing where each node has its own column, as in ours, inorder reads the nodes from left to right.
  • Postorder writes a node once everything below it is written. So the leaves come early, and the root comes last.

5 Three functions, one line apart

Each traversal fills one list. A helper takes a node and adds its subtree to the list, and the main function starts it at the root. The three helpers differ only in where the line that adds node.val sits.

On our tree, the three functions return [1, 2, 4, 5, 3, 6], [4, 2, 5, 1, 3, 6] and [4, 5, 2, 6, 3, 1]. On an empty tree, each returns an empty list.

C++

Pass the vector by reference. The helper takes vector<int>& values. Without the &, each call adds to its own copy, and the values are lost when it returns.

One list for every call. Java passes a reference to the list, so every call adds to the same ArrayList. The list holds Integer, because a List cannot hold a plain int.

A nested function. preorder sits inside the method, so it can append to values without taking it as a parameter. A missing child is None.

An arrow function inside. preorder is defined inside the main function, so it can push to values directly. A missing child is null.

Pass a pointer to the slice. append can move the slice to new memory. So the helper takes *[]int and writes *values = append(*values, node.Val). With a plain []int, the caller would not see the new values.

Borrow the node first. Node is a short name for Option<Rc<RefCell<TreeNode>>>. if let Some(node) is the null check, and node.borrow() gives us val, left and right. The list goes down as &mut Vec<i32>.

One list for every call. The helper takes the List<int> and adds to it, and the method returns it as an IList<int>. A missing child is null.

6 Cost: O(n) time, O(h) space

Time. The walk is at each node three times and does a fixed amount of work each time. It also makes one call on each missing child, and a tree of n nodes has n + 1 of those. So all three orders take O(n) time.

Space. The list is the answer, so we do not count it. The extra space is the call stack, which holds one path from the root. Its size is at most the tree's height h, so the space is O(h).

The height depends on the shape:

1234567
Balanced: 7 nodes on 3 levels
12345
Skewed: 5 nodes on 5 levels
  • A balanced tree has a height of about log n. At n = 10⁵, the stack holds about 17 calls.
  • A skewed tree is a chain, and its height is n. At n = 10⁵, the stack holds 10⁵ calls at its deepest.

A call stack that deep can overflow, and the program stops with a Runtime Error. The next lesson walks the tree with a stack of our own, which avoids this.

7 Mistakes and edge cases

  • No null check. Code that reads node.val before it checks node fails on the empty tree [], at the root itself. That is a Runtime Error.
  • Stopping at leaves instead of at null. A base case of "if both children are null, add the value and return" looks enough. But node 3 is not a leaf, and the walk still calls on its null left child. That call crashes. A null check at the top of the function covers every node.
  • Postorder is not preorder backwards. Our preorder reversed is 6 3 5 4 2 1, but postorder is 4 5 2 6 3 1. Reversing node, left, right gives right, left, node, so the right subtree comes first.
  • Joining lists at every call. This version builds a new list at every node and copies everything below it:
preorder(node)
    if node is null: return []
    left = preorder(node.left)
    right = preorder(node.right)
    return [node.val] + left + right

On a chain of 10⁵ nodes, the copies add up to around 5 × 10⁹ steps, and it gets TLE. One list, passed to every call, avoids the copies.

8 Which order for which job

The sign is a problem that must reach every node. The order depends on where each node's information comes from:

  • Preorder: from the parent. A node is handled before anything below it. That suits copying a tree, because a node must exist before its children can hang from it. It also suits passing something down, such as each node's depth.
  • Postorder: from the children. A node is handled after both its subtrees, so it can use their answers: a height, a size or a sum. Deleting a tree is postorder too, since the children go before the node that points to them.
  • Inorder: from its place, left to right. In a binary search tree, smaller values sit to the left. So inorder gives the values in sorted order, as a later lesson shows.

One order alone does not fix a tree's shape. The preorder 1 2 fits 2 as the left child of 1, and also 2 as the right child. Two orders together can fix it, and a later lesson rebuilds a tree from them.

Before writing a tree walk, ask where each node's information comes from. From above, handle the node before the two calls. From below, handle it after them.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.