Tree Algorithms

How Pre-Order Traversal Works

Pre-order traversal visits a node before its subtrees. That order is what you need to copy a tree or serialise it, because a parent always arrives before the children that hang off it.

40241136554859
Output so far

Nothing yet.

  • Not reached
  • On the stack
  • Current
  • Visited
1/13

Pre-order walk over 7 values, 3 levels deep.

Counters

Visited
0/7
On the stack
0
Tree height
3
Nodes
7

Settings

More options
How it was built

Pre-order

  1. 1stack = [root]
  2. 2while stack:
  3. 3 node = stack.pop()
  4. 4 visit(node)
  5. 5 push node.right
  6. 6 push node.left

What each walk is for

WalkWhat you getTimeExtra space
In-orderValues in sorted orderO(n)O(h)
Pre-orderRoot before children, for copying a treeO(n)O(h)
Post-orderChildren before root, for freeing or evaluatingO(n)O(h)
Level-orderShallowest nodes first, level by levelO(n)O(w)
SearchOne value, by comparing at each nodeO(h)O(1)

Scroll the table sideways for the rest of the columns.

n is the number of values, h the height of the tree and w its widest level. Build the tree from sorted values and h grows all the way to n, which is what balancing prevents.

Complexity

BestAverageWorstExtra memory
O(n)O(n)O(n)O(h)

How pre-order traversal works

Pre-order traversal emits the current node, then walks the left subtree, then the right. Because every parent is emitted before its descendants, the resulting sequence can be replayed to rebuild the tree with the same structure. Insert them in that order and you get the original shape back. In-order cannot do that: its output is sorted, and sorted input builds a completely different tree.

  1. If the node is empty, return.
  2. Visit the node: emit it now, before looking at any child.
  3. Traverse the left subtree in full.
  4. Traverse the right subtree in full.

More tree algorithms