Data Structures · Trees

Binary tree traversal

An array or a linked list has one natural order: first to last. A tree has several. A traversal visits every node exactly once, and the order it chooses is what makes it useful. This page shows the three recursive orders, a picture that explains all three at once, level order, the stack hiding inside recursion, and how to rebuild a tree from two traversals.

Three recursive orders

Every recursive traversal does the same three jobs at each node: handle the left subtree, handle the right subtree, and visit the node itself (here, print its key). The only difference is when the visit happens:

  • Preorder: visit, then left, then right.
  • Inorder: left, then visit, then right.
  • Postorder: left, then right, then visit.

Left always comes before right. Each traversal touches every node once, so each is O(n) time. The recursion uses O(h) stack space, where h is the height of the tree.

// Pre-order traversal: Root, Left, Right
void preorderTraversal(Node* root) {
    if (root != nullptr) {
        cout << root->key << " ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
    }
}

// In-order traversal: Left, Root, Right
void inorderTraversal(Node* root) {
    if (root != nullptr) {
        inorderTraversal(root->left);
        cout << root->key << " ";
        inorderTraversal(root->right);
    }
}

// Post-order traversal: Left, Right, Root
void postorderTraversal(Node* root) {
    if (root != nullptr) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        cout << root->key << " ";
    }
}

What each order is good for

TraversalOrderTypical uses
Preorderroot, left, rightCopying a tree (make the node, then its children). Printing an outline or a folder listing. Writing an expression in prefix form: * + 3 4 5.
Inorderleft, root, rightOn a binary search tree, visits the keys in sorted (non-decreasing) order. Reversed inorder (right, root, left) gives them in descending order. Prints an expression in the usual infix form.
Postorderleft, right, rootDeleting a tree: free the children before their parent. Evaluating an expression tree, since both operands are known before the operator. Computing heights and sizes. Writing postfix form: 3 4 + 5 *.
Level orderby depth, left to rightPrinting a tree level by level. Finding the shallowest node with some property, such as the nearest leaf. Uses a queue, not recursion.
Stop and think
In every one of the three orders, which node is printed first among the leaves? Does the order of the leaves themselves ever change?

The leaves always come out in the same left-to-right order in all three traversals, because left is always handled before right. The traversals only differ in where the internal nodes are slotted in among them.

In preorder, which node is always first? In postorder, which node is always last?

The root is first in preorder and last in postorder. That fact is the key to rebuilding a tree from its traversals, at the end of this page.

One walk explains all three

Imagine walking around the outside of the tree, starting on the left of the root and keeping the tree on your right hand, like tracing its outline with a pencil. You pass every node three times: once on its left side on the way down, once underneath it between its two subtrees, and once on its right side on the way back up. This is called an Euler tour.

Preorder lists the nodes in the order you pass their left sides. Inorder uses the bottoms. Postorder uses the right sides. Pick a traversal and watch the walk.

Recorded order

Stop and think
During the walk, what happens at a leaf? Why are its three visits right next to each other?

A leaf has no subtrees to walk around, so you pass its left side, its bottom and its right side one after another. That is why a leaf appears at the same moment in all three orders relative to its neighbors.

Step through the code

The same tree, run through the actual C++. Watch the call stack: every recursive call is a frame that waits for its children to finish. Level order replaces the stack with a queue, and the last option shows inorder written with an explicit std::stack instead of recursion.

Tree

The tree

Output

Call stack

    What is happening

    Traversal.cpp

      Stop and think
      Run inorder on the expression tree (3 + 4) * 5. What does it print, and why is that a problem?

      It prints 3 + 4 * 5, which most people would read as 3 + 20. The tree knows the + happens first, but plain inorder loses that information. A printer that wraps every operator's subtree in parentheses fixes it. Preorder (* + 3 4 5) and postorder (3 4 + 5 *) need no parentheses at all.

      Compare "Inorder" and "Inorder with a stack" on the same tree. When does the iterative version push a node, and when does it print it?

      It pushes each node on the way down its left spine, and prints a node when it is popped, which happens only after everything to its left is done. That is exactly the moment the recursive version reaches its cout line: the explicit stack holds the same nodes as the call stack would.

      On the skewed tree, how deep does the call stack get? What would happen with a skewed tree of a million nodes?

      As deep as the tree is tall: one frame per node on the chain. With a million nodes that is a million nested calls, which would overflow the program's call stack and crash it. An iterative version with an explicit stack, or keeping the tree balanced, avoids this.

      Predict it

      Here is a random tree. Type the order you think the chosen traversal produces, separated by spaces, then press Check. If you are wrong, the first mistake is highlighted.

      Rebuilding a tree from two traversals

      One traversal is not enough to pin down a tree: the tree 1 with left child 2, and the tree 1 with right child 2, both have preorder 1 2. But preorder plus inorder determines the tree exactly, as long as the keys are all different:

      1. The first key in the preorder is the root.
      2. Find that key in the inorder. Everything to its left is the left subtree; everything to its right is the right subtree.
      3. That tells you how many keys each subtree has, so the preorder splits the same way: after the root come the left subtree's keys, then the right subtree's.
      4. Repeat on each half until the pieces are empty.

      Postorder plus inorder works the same way, using the last key as the root. Preorder plus postorder is not enough in general: a node with a single child could have it on either side.

        Stop and think
        Rebuild the tree from preorder A B D E C F and inorder D B E A F C by hand, then check it with the tool.

        A is the root. In the inorder, D B E are on its left and F C on its right. The left part's preorder is B D E: B is its root with D left and E right. The right part's preorder is C F: C is its root, and F is to C's left in the inorder, so F is C's left child.

        Why does the method need the keys to be distinct?

        Step 2 finds the root's key in the inorder. With repeated keys there can be several matches, and different choices give different trees, so the answer is no longer unique.