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.

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

Leave a Reply