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.
Asked
Active
Viewed 6.0k times
1
-
2Just similar as the other languages. – Weibo Li Feb 12 '14 at 04:30
-
pls give some examples and reference to create – Sathesh Feb 12 '14 at 04:31
-
[this might help](http://stackoverflow.com/questions/3522454/java-tree-data-structure) – prime Feb 12 '14 at 04:35
-
Google `Java Tree examples` and you will find this: http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html – ubiquibacon Feb 12 '14 at 04:36
-
what are you exactly trying to achieve is very unclear – D3X Feb 12 '14 at 04:38
-
[possible solution](http://stackoverflow.com/questions/3522454/java-tree-data-structure) – D3X Feb 12 '14 at 04:39
-
off-topic because you are asking "do this for me"... – Not a bug Feb 12 '14 at 05:28
2 Answers
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