LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

How does a preorder traversal work, and what is it used for?

Preorder visits a node before its descendants: visit the node, then recursively traverse each child's subtree from left to right. A typical use is printing a structured document, where each heading must come before its contents.

A report outline numbered in preorder

* Each heading is printed before anything inside it, so preorder reproduces the reading order. *

Algorithm preOrder(v)
  visit(v)
  for each child w of v
    preOrder(w)

The name says where the visit happens: pre, before the recursive calls. So the root is always visited first, and a node's whole subtree is finished before its next sibling starts.

For a document, that is exactly the order you read it in: title, chapter 1, section 1.1, section 1.2, chapter 2, its sections, then the references. A table of contents is a preorder traversal of the document's tree.

From Quiz: ADS / Trees: Structure, Storage and Traversals | Updated: Sep 29, 2026