14

I understand pre-order, in-order, and post-order tree traversal algorithms just fine. (Reference). I understand a few uses: in-order for traversing binary search trees in order, pre-order for cloning a tree. But I can't for the life of me come up with a real world task that I'd need post-order traversal to accomplish.

Can you give me an example? And: can you give me any better uses for pre-order traversal?

Edit: Can anyone give me an example other than expression trees and RPN? Is that really all post-order is good for?

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
Plutor
  • 2,867
  • 2
  • 25
  • 29

2 Answers2

17

Topological sorting is a post-order traversal of trees (or directed acyclic graphs).

The idea is that the nodes of the graph represent tasks and an edge from A to B indicates that A has to be performed before B. A topological sort will arrange these tasks in a sequence such that all the dependencies of a task appear earlier than the task itself. Any build system like UNIX make has to implement this algorithm.

The example that Dario mentioned — destroying all nodes of a tree with manual memory management — is an instance of this problem. After all, the task of destroying a node depends on the destruction of its children.

Heinrich Apfelmus
  • 11,034
  • 1
  • 39
  • 67
  • This is a great answer. Remembering that trees are degenerate graphs opens up all kinds of functionality. And topological sorting is hugely useful. – Plutor Aug 23 '10 at 13:57
  • Why is it called topological sorting instead of, say, scheduling or something, or what is "Topological" supposed to mean in this context? – Shawn Apr 30 '11 at 03:08
  • @Shawn: Beats me. It's probably because only the topology of the graph/network matters. – Heinrich Apfelmus May 03 '11 at 18:12
4

As Henk Holterman pointed out, destroying a tree using manual memory management usually is a post-order traversal.

Pseudocode:

destroy(node) {
  if (node == null) return;

  destroy(node.left)
  destroy(node.right)

  // Post-order freeing of current node
  free(node)
}
Dario
  • 48,658
  • 8
  • 97
  • 130