views:

1789

answers:

3

I want to construct a general tree in java in which one root node and which can have a n children and each node can contain sub trees. How do I get started?

+4  A: 

Pretty simple, should be something like this. You have a Node class:

public class Node {
    private String nodeValue; // or any other type of value you want the nodes to have
    private List<Node> childNodes;

    // constructors

    // getters/setters
}

And a Tree class:

public class Tree {
    private Node rootNode;

    // constructors

    // tree methods
}

Note that the nodes are not limited as to how many child nodes they have, so this gives the n-ary tree you are looking for.

Yuval A
+1  A: 

you could easily extend Yuval A's answer to use generics:

    public class Node<T> {
    private T nodeValue;
    private List<Node<T>> childNodes;

    // constructors

    // getters/setters
}

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

    // constructors

    // tree methods
}
shsteimer
+1  A: 

According to Yuval's answer, I would prefer the following solution:

public class Tree {
  private String nodeValue;
  private List<Tree> subTrees;

  // the methods
}

So your recursion is implemented in your Tree class. You can see each part of the tree as a single tree. It's easier to understand.

You should consider to read a book about data structures, even if it's homework. I'm sure you will not understand how Trees work if we post you a pice of code.

furtelwart