Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real world pre/post-order tree traversal examples

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?

like image 846
Plutor Avatar asked Aug 20 '10 15:08

Plutor


People also ask

What is preorder traversal technique with an example?

Preorder traversal It means that, first root node is visited after that the left subtree is traversed recursively, and finally, right subtree is recursively traversed. As the root node is traversed before (or pre) the left and right subtree, it is called preorder traversal.

Which of the following is application of preorder traversal of a tree?

Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on an expression tree.

Why is preorder traversal useful?

Pre-order traversal is useful when we're searching for an element within a binary search tree. We can use the root nodes value to determine if we need to search the right or left subtree next.

Where is tree traversal used?

Each node is freed after freeing its children. In-order traversal is very commonly used on binary search trees because it returns values from the underlying set in order, according to the comparator that set up the binary search tree.


2 Answers

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.

like image 98
Heinrich Apfelmus Avatar answered Sep 20 '22 13:09

Heinrich Apfelmus


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)
}
like image 30
Dario Avatar answered Sep 22 '22 13:09

Dario