Generic tree implementation in Java

Ivan Koblik picture Ivan Koblik · Aug 31, 2009 · Viewed 70.9k times · Source

Is anyone aware of a generic tree (nodes may have multiple children) implementation for Java? It should come from a well trusted source and must be fully tested.

It just doesn't seem right implementing it myself. Almost reminds me of my university years when we were supposed to write all our collections ourselves.

EDIT: Found this project on java.net, might be worth looking into.

Answer

Zed picture Zed · Aug 31, 2009

Here it comes:

abstract class TreeNode implements Iterable<TreeNode> {

  private Set<TreeNode> children;

  public TreeNode() {
    children = new HashSet<TreeNode>();
  }

  public boolean addChild(TreeNode n) {
    return children.add(n);
  }

  public boolean removeChild(TreeNode n) {
    return children.remove(n);
  }

  public Iterator<TreeNode> iterator() {
    return children.iterator();
  }
}

I am well trusted, but haven't tested the implementation.