1

I want to know how to create own tree in java, it consists of eight sub-nodes and in each sub-node it having many sub-nodes. How to create this. please help me. I am newer to java.

dkb
  • 4,389
  • 4
  • 36
  • 54
Sathesh
  • 378
  • 1
  • 4
  • 13

2 Answers2

13

You'll probably need to create some sort of Node class to represent the nodes in the tree:

public class Node
{
    private List<Node> children = null;
    private String value;

    public Node(String value)
    {
        this.children = new ArrayList<>();
        this.value = value;
    }

    public void addChild(Node child)
    {
        children.add(child);
    }

}

Then to populate your tree:

public static void main(String [] args)
{
    Node root = new Node("root");
    root.addChild(new Node("child1"));
    root.addChild(new Node("child2")); //etc.
}

You'll have to modify this to suit your own purposes, this code is just to give you an idea of the structure.

therealrootuser
  • 10,215
  • 7
  • 31
  • 46
2

A good design will be : Create a class RootNode with array of eight references to another class FirstLevelChildNode which in turn has dynamic array (say ArrayList) of another class ChildNodes, with required operations in each class...

user3297129
  • 299
  • 1
  • 6
  • You really only need one type of node, since subtrees are trees themselves, and it'd get difficult to tell roots from first children recursively. – Makoto Feb 12 '14 at 04:44
  • Yes I agree to that. We can have a constant integer that restricts the no of children a node can have instead of having a different class. – user3297129 Feb 13 '14 at 10:21