Practice Discrete Math

Algorithms / Tree Traversal Recursion

Least You Need to Know: Tree Traversals and Recursive Calls

Tree interview questions often hinge on when work happens relative to the recursive calls. Preorder acts before the children, inorder acts between them, and postorder acts after the children return.

Least you need to know

  • Preorder visits a node before recursively processing its children.
  • Inorder is specific to binary trees and visits left subtree, node, then right subtree.
  • Postorder visits children before the current node and is natural for bottom-up aggregation or deletion.
  • Recursive tree traversal depth is controlled by the tree height.
  • A stack-based iterative DFS simulates the same call-stack idea explicitly.

Key notation

  • preorder — node before children
  • inorder — left subtree, node, right subtree in a binary tree
  • postorder — children before node

Worked example

  • Suppose you need to print a binary tree in sorted order and the tree is a BST.
  • The BST property says every left value is smaller and every right value is larger.
  • So an inorder traversal prints all smaller values, then the root, then all larger values.
  • That is why inorder is the default sorted-output traversal for BSTs.

Common mistakes

  • Students often use inorder on non-binary trees even though the notion does not naturally apply there.
  • Students often forget that postorder is the natural direction for computing answers from child answers.
  • Students often confuse the recursion depth with the number of nodes.

How to recognize it

  • If the question says act on a node before exploring descendants, think preorder.
  • If the question is about BST sorted output, think inorder.
  • If the parent answer depends on completed child answers, think postorder.

Next recommended lesson

Continue through this topic with Least You Need to Know: Trie vs Hash vs KMP Tradeoffs for String Tasks.

Least You Need to Know: Trie vs Hash vs KMP Tradeoffs for String Tasks

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

Start practice