4

What are some examples of when to use preorder/postorder practically? When does it make more sense than in-order?

Amna Rajpoot
  • 55
  • 1
  • 5
  • 1
    Whatever you want in your application. This is like asking when you should drink beer, orange juice or water. – gnasher729 Oct 27 '18 at 05:48
  • 1
    You use whichever gives you the results you need. Your question is like asking "What are some examples of when to use subtraction/multiplication practically? When does it make more sense than addition?" – David Richerby Oct 27 '18 at 09:30

1 Answers1

4

"Whatever you want in your application. This is like asking when you should drink beer, orange juice or water", commented by one wise user, Gnasher729.

"You use whichever gives you the results you need. Your question is like asking 'What are some examples of when to use subtraction/multiplication practically? When does it make more sense than addition?'", commented by another wise user, David Richerby.

What do the above similes mean exactly? If you have understood what are preorder/postorder and inorder traversals clearly, it becomes obvious for you to choose which one make more sense to use.

So the best answer could simply be reviewing the definition of those traversals. Here is one way to understand them in the usual context of binary trees.

  • A preorder traversal visits the root node first, followed by a preorder traversal of the left subtree, followed by a preorder traversal of the right subtree.

  • An inorder traversal does an inorder traversal on the left subtree, followed by a visit to the root node, followed by an inorder traversal of the right subtree.

  • A postorder traversal does a postorder traversal of the left subtree, followed by a postorder traversal of the right subtree, followed by a visit to the root node.

In a nutshell, each traversal traverses a binary tree recursively. The "pre/in/post" refers to when the root node, which store the value in the middle, is visited, which is first, between first and last, and last respectively. Note that left subtree is always visited before right subtree.

Understanding cannot be solid without relevant examples and exercises. You may check for example chapter 12, "Binary Search Trees" of CLRS to find some.

Here are some usual usage examples.

  • Preorder traversal is used to get prefix expression on of an expression tree, Polish notation
  • Postorder traversal is used to get postfix expression of an expression tree, reverse Polish notation
  • In case of binary search trees, inorder traversal will traverse nodes in non-decreasing order. This is probably the easiest result if not the most common result. To traverse nodes in non-increasing order, inorder traversal but visiting right subtree before left subtree can be used.
John L.
  • 38,985
  • 4
  • 33
  • 90