Walking a tree

void preorder(Node node) {
  if (node == null) return;
  System.out.print(node + " ");
  preorder(node.left);
  preorder(node.right);
}


void postorder(Node node) {
  if (node == null) return;
  postorder(node.left);
  postorder(node.right);
  System.out.print(node + " ");
}


void inorder(Node node) {
  if (node == null) return;
  inorder(node.left);
  System.out.print(node + " ");
  inorder(node.right);
}
I don't find this pleasant. The details of what you want to do are jumbled up with the details of the recursion, plus we need to know the details of the tree itself.

The Ruby solution, passing a block in and letting the tree apply that to its elements, does start to look attractive. But which order is the right order. I went hunting for a Ruby example and found an example which implements the each in a way that "looks right". Hmmm. Remember "As long as your class defines a sensible each method, you can use a for loop to traverse it." and that lots of Ruby methods build on each. The Ruby solution to this (and I'm not a big Ruby expert) appears to be mutating the class instance to add or modify an existing method. Not, I don't think, deriving a new type but modifying an existing type at runtime. Make me feel queasy, but today's young kids just tell me I'm old fashioned.

If, we as people with weak stomachs for that kind of thing, provide a set of iterators for the tree we can walk the tree in a comfortable way.