Learn / Trees

Traversals

Preorder visits a node, then its left subtree, then its right. Inorder visits left, node, right. Postorder visits left, right, node. Recursion writes each in three lines; with an explicit stack, each can also be done iteratively, which avoids deep call stacks and is a common interview follow-up.

How to recognise it

  • The answer is a list of all node values in some order.
  • You must process children before the parent (postorder) or the parent before children (preorder).
  • A BST's sorted order is wanted (inorder).

The three depth-first orders

1234567
Preorder 1 2 4 5 3 6 7, inorder 4 2 5 1 6 3 7, postorder 4 5 2 6 7 3 1, level order 1 2 3 4 5 6 7.

What a node, a child, a leaf and a level are is on the Structures page.

OrderRuleFor the tree above
preordernode, left, right1 2 4 5 3 6 7
inorderleft, node, right4 2 5 1 6 3 7
postorderleft, right, node4 5 2 6 7 3 1
visit(n):
    if n is null: return
    (preorder: record n here)
    visit(n.left)
    (inorder: record n here)
    visit(n.right)
    (postorder: record n here)

Without recursion

  • Preorder: a stack; pop a node, record it, push its right then its left.
  • Inorder: walk left pushing nodes; pop one, record it, move to its right child; repeat.
  • Postorder: do "node, right, left" with the preorder method and reverse the result.

All of them are O(n) time and O(h) extra space, where h is the height.

Common mistakes

  • Pushing the left child first in the iterative preorder.
  • Forgetting that a skewed tree makes h = n, so deep recursion can overflow.

Problems

0 of 4 solved

Check yourself

For the tree 1 (2 (4, 5), 3), what is the inorder?

Which traversal is natural for deleting a tree?

In the iterative preorder, why is the right child pushed before the left?

How does one iterative loop give all three orders?