Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use inorder, preorder and postorder traversal

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!

like image 421
user1054740 Avatar asked Feb 07 '13 07:02

user1054740


People also ask

What is the use of inorder preorder Postorder traversal?

Pre-order traverse gives the node values in a sequence of insertion. If you want to create a copy of the tree you need to traverse the source tree in this way. In-order traverse gives the sorted node values. As to post-order traverse you can use this method to delete entire tree cause it visits leaf nodes first.

Why do we need inorder traversal?

Uses of Inorder Traversal: In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal is reversed can be used. Example: In order traversal for the above-given figure is 4 2 5 1 3.

What is the difference between inorder preorder and postorder traversal?

For Inorder, you traverse from the left subtree to the root then to the right subtree. For Preorder, you traverse from the root to the left subtree then to the right subtree. For Post order, you traverse from the left subtree to the right subtree then to the root.

Which tree traversal is most efficient?

Inorder Traversal. Inorder Traversal is the one the most used variant of DFS(Depth First Search) Traversal of the tree.


1 Answers

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)).

like image 70
Jerry Coffin Avatar answered Jan 03 '23 13:01

Jerry Coffin