Trees - Preorder, Inorder, Postorder

If you partook in the beginner lessons in software development, we will be familiar with binary trees. We will explore this topic more in depth in this section. To begin, why don't we review what a tree looks like.

binary tree

A binary tree consists of nodes where each node at a minimum contains some data as well as a pointer for a left and right child. Given a root node, we may traverse the tree in various ways to extract information.

We also define a node and a way to construct a tree from a list of nodes as following.

Using recursion, there are three methods for traversal, where the primary distinction is the order in which nodes are visited:

  • pre-order: A current node is visited first, followed by a left subtree and then a right subtree.
  • in-order: A left subtree is visited first, followed by a current node, and then a right subtree.
  • post-order: A left subtree is visited first, followed by a right subtree, and then a current node.

We will look at an example along with a relative strength for each.

Imagine we want to create a horizontal bridge at some specified depth. Pre-order traversal will help us get the path of nodes right. Using the tree in the image above, and a target depth of two, we should expect a bridge to be built along Node(4) -> Node(5) -> Node(6).

As we will learn in the next lesson on binary search trees, in-order traversal may be used to print the values of such tree in sorted order.

Now imagine we want to find a minimum path in a perfect binary tree. A minimum path is a path between root and leaf such that the sum of the node values is smallest among all possible paths. A perfect binary tree is one where all nodes, including leafs, are filled. Because post-order traversal looks at both subtree's, we may determine a minimum value between each, and recurse up to get the minimum path.