$\begingroup$
"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.
Suggested reading: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.
I realized recently that while having used BST's plenty in my life, I've never even contemplated using anything but Inorder traversal (while I am aware of and know how easy it is to adapt a program to use pre/post-order traversal).
Upon realizing this, I pulled out some of my old data-structures textbooks and looked for the reasoning behind the usefulness of pre-order and post-order traversals - they didn't say much though.
What are some examples of when to use preorder/postorder practically? When does it make more sense than in-order?
Previous: Is BFS preorder or postorder?
Comments
Please Join Us to post.
0