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.

7
  • 2
    Just similar as the other languages. Commented Feb 12, 2014 at 4:30
  • pls give some examples and reference to create Commented Feb 12, 2014 at 4:31
  • this might help Commented Feb 12, 2014 at 4:35
  • Google Java Tree examples and you will find this: docs.oracle.com/javase/tutorial/uiswing/components/tree.html Commented Feb 12, 2014 at 4:36
  • what are you exactly trying to achieve is very unclear Commented Feb 12, 2014 at 4:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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...

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.