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.
2 Answers
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.
Comments
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
Makoto
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.
user3297129
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.
Java Tree examplesand you will find this: docs.oracle.com/javase/tutorial/uiswing/components/tree.html