Trees

We have, so far, taken it more or less as read that an iterator works over a linear collection. It starts at the beginning and steps, one thing at a time, until it gets to the end, and then it stops. That does seem entirely sensible. Natural, even.

But not all containers are straight forward lists, and not every traversal is linear. We might have other data structures we need to traverse, like this lovely tree.

Does it make sense to do for each on a tree? Not in the general case, no, there is no right way.

For this tree here, there three different ways: preorder; postorder; in-order; which yield three different results. Often tree walking is handled in a recursive manner. Here's some Java code to do this.