How to implement a tree data-structure in Java?

ikl picture ikl · Aug 19, 2010 · Viewed 716.3k times · Source

Is there any standard Java library class to represent a tree in Java?

Specifically I need to represent the following:

  • The sub-tree at any node can have an arbitrary number of children
  • Each node (after the root) and it's children will have string value
  • I need to get all the children (some sort of list or array of Strings) of a given node and it's string value(i.e. a method that will take a node as input and return all the string values of the children node as output)

Is there any available structure for this or do I need to create my own (if so implementation suggestions would be great).

Answer

jjnguy picture jjnguy · Aug 19, 2010

Here:

public class Tree<T> {
    private Node<T> root;

    public Tree(T rootData) {
        root = new Node<T>();
        root.data = rootData;
        root.children = new ArrayList<Node<T>>();
    }

    public static class Node<T> {
        private T data;
        private Node<T> parent;
        private List<Node<T>> children;
    }
}

That is a basic tree structure that can be used for String or any other object. It is fairly easy to implement simple trees to do what you need.

All you need to add are methods for add to, removing from, traversing, and constructors. The Node is the basic building block of the Tree.