6

I understand the code behind how to do inorder, preorder, and postorder traversal on a binary search tree. However, I'm confused about the application.

When would you use each? It would be really helpful to illustrate cases of when each method of traversal makes the most sense.

Thanks!

user1054740
  • 503
  • 2
  • 7
  • 13
  • Possible duplicate of [When to use Preorder, Postorder, and Inorder Binary Search Tree Traversal strategies](http://stackoverflow.com/questions/9456937/when-to-use-preorder-postorder-and-inorder-binary-search-tree-traversal-strate) – Simon Featherstone Nov 24 '16 at 13:52

1 Answers1

10

Inorder traversal simply processes the items in the defined order. If, for example, you have a BST of a list of words or names, inorder traversal would print them out in order.

Preorder and postorder traversal most often apply to trees other than binary search trees. For example, to evaluate an expression like A + B * C, you can create a tree like this:

enter image description here

To evaluate the expression, you traverse the tree in postorder, applying each operator to the values from each of its sub-trees.

Preorder traversal could be used for roughly the same purpose if you wanted (for example) to produce output in a language something like Lisp, so the expression should come out as (add A (mul B C)).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111