Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Different types of iterator implementation to visit a BST. Theoretical Question

To visit a BST through an iterator there are preferences on the order to follow to scroll? To me I have always been told to do it IN ORDER.

I would like to understand if this implementation is used exclusively to maintain the order of the tree or for other reasons regarding maybe other operations done to the structure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you need to traverse the values of a binary search tree in their proper order, you need indeed an in-order traversal.

In other circumstances you’d want to use a different order, but often for purposes unrelated to the fact that the tree is a binary search tree.

For example:

If you need to get the height of each node (i.e. its distance to its furthest leaf), you’d want to visit the children before visiting the parent, so that the parent’s height can be derived from the children’s heights. For that a post-order traversal would suit best.

If you need to get the depth of each node (i.e. its distance to the root), you’d want to visit the parents before visiting their children, so that the child’s depth can be derived from its parent’s depth. So for that a pre-order traversal or level-order traversal would suit best.

If you need to find the shortest path from the root to a node that has some particular condition, you’d want to use a breadth-first search, which means you would perform a level-order traversal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading