Iteration over a sorted binary tree using recursive descent in an enumeration method.
- By Kevlin Henney
- September 24, 2001
Patterns in Java
A tale of three patterns
by Kevlin Henney
Listing 1. Iteration over a sorted binary tree using recursive descent in an enumeration method.
public interface KeyValueTask
{
void apply(String key, String value);
}
public class SortedBinaryTree
{
public synchronized void forEachDo(KeyValueTask toDo)
{
forEachDo(toDo, root);
}
private void forEachDo(KeyValueTask toDo, Node node)
{
if(node != null)
{
forEachDo(toDo, node.left);
toDo.apply(node.key, node.value);
forEachDo(toDo, node.right);
}
}
...
}
tree.forEachDo(new KeyValueTask() {
public void apply(String key, String value)
{ System.out.println(key + " -> " + value); }
});
About the Author
Kevlin Henney is a Principal Technologist with QA Training in the UK.