Iteration over a sorted binary tree using recursive descent in an enumeration method.

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.

Featured

Most   Popular
Upcoming Events

AppTrends

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.