Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tree traversal. Inorder, preorder, postorder

I understand the idea behind the tree traversal as well as implementations, but here is the question. Why do we need them all?

Right now I only know that preorder traversal is used when parsing math expressions. From the Wikipedia I also read than:

  • Inorder traversal is particularly common to use an inorder traversal on a binary search tree because this will return values from the underlying set in order, according to the comparator that set up the binary search tree (hence the name). Preorder traversal
  • Traversing a tree in preorder while inserting the values into a new tree is common way of making a complete copy of a binary search tree. One can also use preorder traversals to get a prefix expression (Polish notation) from expression trees: traverse the expression tree preorderly. (which I already stated)

But these examples are rather vague. Can anyone describe this in more depth. Especially with examples.

like image 670
Salvador Dali Avatar asked Jan 16 '23 10:01

Salvador Dali


1 Answers

Consider the problem of doing some file operation on a directory tree. When the operation is removal of files, then you need to empty each directory before removing the directory itself, so you need a post-order traversal. By contrast, when copying the hierarchy, you need to copy the directories first, so then you need a pre-order traversal.

I honestly don't see what's vague about the BST in-order traversal. When you want to display the contents of a BST on-screen in a user interface, you want the keys to show up sorted, don't you? (If you didn't, then using a BST would probably be a bad idea since a hash table is often faster.)

like image 128
Fred Foo Avatar answered Jan 23 '23 20:01

Fred Foo