I want to realize DFS for my own generic tree with my own nodes.
Nodes have this fields
private T value;
private final List<Node<T>> listOfChildren;
And Tree.class has only Node root field.
My DFS realization is working fine, but it's my first work with iterator and I don't understand how I should #Override methods.
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class DFSAlgorithm<T> implements Iterator<T> {
private final Stack<Iterator<T>> stack = new Stack<>();
private List<Node<T>> listOfChildren;
public void DFS(Node<T> vertex) {
System.out.println("DFS start");
Stack<Node<T>> stack = new Stack<>();
stack.push(vertex);
while (!stack.isEmpty()) {
Node<T> node = stack.pop();
System.out.println(node.getValue());
for (Node<T> tNode : node.getListOfChildren()) {
stack.push(tNode);
}
}
}
#Override
public void remove() {
throw new ConcurrentModificationException();
}
#Override
public boolean hasNext() {
return this.listOfChildren != null;
}
#Override
public T next() {
return null;
}
}
My Node.class
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private T value;
private final List<Node<T>> listOfChildren;
public Node(){
super();
listOfChildren = new ArrayList<Node<T>>();
}
public Node(T value){
this();
setValue(value);
}
public T getValue() {
return value;
}
public List<Node<T>> getListOfChildren() {
return listOfChildren;
}
public void setValue(T value) {
this.value = value;
}
public int getNumberOfChildren() {
return listOfChildren.size();
}
public void addChildren(Node<T> child) {
listOfChildren.add(child);
}
}
I don't understand where I should write Node and where I should write Iterable.
Should I write this methods for stack in DFS or for Tree?
Can you explain this, please, I'm new in java
As #Rogue has said in the comments, your Tree should implement interface Iterable, i.e. it needs to override iterator() method, which is meant to provide a mean of traversal over this tree.
DFSAlgorithm in turn should be an Iterator, i.e. MyTree.iterator() would return a new instance of DFSAlgorithm. And DFSAlgorithm needs to implement the contract of the Iterator interface by overriding methods next() and hasNext().
There's a few things to note:
Method DFS() is not needed. The logic of Depth first search algorithm should be reflected in the implementations of next() and hasNext() (by the way, method name DFS() is not aligned with Java naming conventions).
A Stack, which is used a mean of traversal in DFS algorithm, should be an instance variable of the iterator implementation (no need to create another instantiate of the stack as you've done and store it in a local variable). And Stack should be populated with the root-node of the Tree while instantiating the iterator.
Field List<Node<T>> listOfChildren is redundant, it's not required in the classic DFS implementation and in this case as well. Having only a Stack is sufficient to perform traversal of a Tree.
Class java.util.Stack is legacy and not recommenced to be used. Instead, when you need an implementation of the Stack data structure, it's advisable to utilize implementations of the Deque interface.
Method remove() has a default implementation which throws UnsupportedOperationException (which is semantically more suitable, than ConcurrentModificationException that can be observed in your code). If you're not going to implement the functionality for removing nodes by the means of iterator, there's no need to override this method.
ConcurrentModificationException is meant to guard against structural modifications (i.e. modifications that affect the size of the data structure) that happen during the iteration process, which can lead to the situation when iteration is unaware of the actual state of the data structure. The common practice is to introduce a couple of modification counters and compare their values at the very beginning of the call Iterator.next(). If you wonder how it might be implemented, have a look at the standard Collections from JDK.
That's how the implementation might look like:
public class MyTree<T> implements Iterable<T> {
private Node<T> root;
// constructor of the Tree, etc.
#Override
public Iterator<T> iterator() {
return new DFSAlgorithm<>(root);
}
public class DFSAlgorithm<T> implements Iterator<T> {
private final Deque<Node<T>> stack = new ArrayDeque<>();
public DFSAlgorithm(Node<T> vertex) {
this.stack.push(vertex);
}
#Override
public boolean hasNext() {
return !stack.isEmpty();
}
#Override
public T next() {
Node<T> next = stack.pop();
for (Node<T> tNode: next.getListOfChildren()) {
stack.push(tNode);
}
return next.getValue();
}
}
public class Node<T> {
// you code without changes here
}
}
Related
One of the advantages of streams is that you can avoid visiting the whole structure for some operations, like anyMatch or filter+findFirst.
However, if you have your own data structure, depending on how you turn it into a stream you may end up visiting it all anyway.
What is the right way to turn a custom tree data type into a stream?
Consider the following example:
interface Tree{
void forEach(Consumer<Integer> c);
}
final class EmptyTree implements Tree{
public void forEach(Consumer<Integer> c){}
}
interface NonEmptyTree extends Tree{}
record Leave(int label) implements NonEmptyTree{
public void forEach(Consumer<Integer> c){
System.out.println("In forEachLeave "+label);
c.accept(label);
}
}
record Node(NonEmptyTree left, NonEmptyTree right) implements NonEmptyTree{
public void forEach(Consumer<Integer> c){
left.forEach(c); right.forEach(c);
}
}
The two main ways to turn a tree into a stream would be
var sb=Stream.<Integer>builder();
myTree.forEach(sb);
sb.build()
or
Stream.of(myTree).mapMulti(Tree::forEach)
However, both of them call forEach, thus both of them will visit all the tree (and call the prints for all the labels, in this example).
How do you implement a .stream() method in the Tree type so that it would not even visit the whole tree if it is not needed? (because of .anyMatch, for example)
Ok, I sorted it.
I'm quite sure that what I'm doing is pretty standard with immutable trees
(parent fields only make sense in mutable trees)
Here is my result, for reference for future programmers doing streams on immutable trees.
The class TreeIterator<E> is the one really relevant to this ordeal.
I could make nested classes to be able to make more stuff private, but as a code example I think it is more clear in this non nested form.
interface Tree<E> extends Iterable<E>{
Tree<E> and(Tree<E> other);
default Tree<E> left(){ return empty(); }
default Tree<E> right(){ return empty(); }
default E label(Supplier<E> orElse){ return orElse.get(); }
#SuppressWarnings("unchecked")
static <E> Tree<E> empty(){ return (Tree<E>)EmptyTree.empty; }
static <E> Tree<E> leaf(E label){ return new Leaf<E>(label); }
default Stream<E> stream(){ return StreamSupport.stream(spliterator(), false); }
}
final class EmptyTree<E> implements Tree<E>{
public Tree<E> and(Tree<E> other){ return other; }
private EmptyTree(){} //Singleton pattern: only one EmptyTree can exists
static final Tree<?> empty = new EmptyTree<>();
public Iterator<E> iterator(){ return List.<E>of().iterator(); }
public String toString(){ return "<EMPTY>"; }
}
interface NonEmptyTree<E> extends Tree<E>{
Leaf<E> itAdvance(ArrayList<NonEmptyTree<E>> stack);
default Tree<E> and(Tree<E> other){
if (!(other instanceof NonEmptyTree<E> net)){ return this; }
return new Node<E>(this, net);
}
}
record Leaf<E>(E label) implements NonEmptyTree<E>{
public E label(Supplier<E> orElse){ return label; }
public Leaf<E> itAdvance(ArrayList<NonEmptyTree<E>> stack){ return this; }
public Iterator<E> iterator(){ return List.<E>of(label).iterator(); }
public String toString(){ return label+""; }
}
record Node<E>(NonEmptyTree<E> left, NonEmptyTree<E> right) implements NonEmptyTree<E>{
public Node{ assert left!=null && right!=null; }//null is not a valid tree
public Leaf<E> itAdvance(ArrayList<NonEmptyTree<E>> stack){
stack.add(right);
return left.itAdvance(stack);
}
public Iterator<E> iterator(){ return new TreeIterator<E>(this); }
public String toString(){ return "("+left+", "+right+")"; }
}
class TreeIterator<E> implements Iterator<E>{
private final ArrayList<NonEmptyTree<E>> stack = new ArrayList<>(32);
public boolean hasNext(){ return !stack.isEmpty(); }
public TreeIterator(Node<E> n){ stack.add(n); }
public E next(){
if(stack.isEmpty()){ throw new NoSuchElementException(); }
var last=stack.remove(stack.size()-1);
return last.itAdvance(stack).label();
}
}
Looking at record definition Leave(int label) implements NonEmptyTree, I have two questions:
Did you mean "leaf"?
A tree consists of nodes (either a leaf or an internal node), but a node or leaf do not implement a tree, i.e., they are not are specific type of a tree. Are you sure about your node/leaf/tree implementation?
I would recommend a simple implementation like this one here: https://www.baeldung.com/java-binary-tree
When it comes to stream, you have two options:
Implement your own Stream-enabled class (see discussion here)
Provide a method that returns a (specific) stream, e.g. filtered.
Keep in mind that there are many different trees out there, e.g. red–black tree, n-ary tree, AVL Tree, B-Tree ...
I want to use a domain specific tree DomainTree consisting of Domain specific Nodes DomainNode, but keep all generic functions in template classes Tree and Node. First I started with the templates Tree<T> and Node<T> (where T is the type of a nodes data). The DomainTree was then working with the Node<T> interface, which was not what I wanted. It should work on DomainNode objects instead.
To cope with that, I changed the generic tree's template parameter to Tree<N extends Node<?>> (the implementation below). Now I can work with the DomainNode by instantiating the tree as DomainTree<DomainNode>.
Still, I get a compilation error at (1) because getChildren() returns a list of Node<T>, which doesn't seem to be convertible to a list of N, though I made sure that N extends Node<?>.
Why is this not working and how can I design it, so that the DomainTree can work with DomainNodes?
Generic Tree
import java.util.ArrayList;
import java.util.List;
class Tree<N extends Node<?>> {
public N rootElement;
public List<N> toList() {
List<N> list = new ArrayList<N>();
walk(rootElement, list);
return list;
}
private void walk(N element, List<N> list) {
list.add(element);
List<N> children = element.getChildren(); // (1) Cannot convert from List<Node<T>> to List<T>
for (N data : children) {
walk(data, list);
}
}
}
class Node<T> {
public T data;
public List<Node<T>> children;
public List<Node<T>> getChildren() {
if (this.children == null) {
return new ArrayList<Node<T>>();
}
return this.children;
}
public void addChild(Node<T> child) {
if (children == null) {
children = new ArrayList<Node<T>>();
}
children.add(child);
}
}
Problemspecific Tree
class DomainTree extends Tree<DomainNode> {
public void build() {
for (DomainNode node : toList()) {
// process...
}
}
}
class DomainNode extends Node<String> {
}
The problem with the code as it stands is that for a given Node<T>, the compiler has no way of knowing that the type of the List returned from toList() is the same Node<T> as the class itself.
What you need is a self-referencing generic type:
class Node<T, N extends Node<T, N>> {
public T data;
public List<N> children;
public List<N> getChildren() {
return children == null ? Collections.<N>emptyList() : children;
}
public void addChild(N child) {
if (children == null) {
children = new ArrayList<N>();
}
children.add(child);
}
}
Now the type returned from toList() is the same type as the type itself.
Then DomainNode becomes:
class DomainNode extends Node<String, DomainNode> {
//
}
And the signature of of Tree changes slightly to become:
class Tree<N extends Node<?, N>> {
And your usage example now compiles:
class DomainTree extends Tree<DomainNode> {
public void build() {
for (DomainNode node : toList()) {
// process...
}
}
}
I added in a couple of other efficiencies too.
generics hold some surprises if you are not really into it. At first keep in mind that there is a type erasure and the compiler and the runtime thus see different things. Roughly spoken this also limits the compiler abilities in analyzing source code.
Note that there is really a difference between a List<Node<N>> and a List<N>. Hence even with N extends Node<?> the assignment 'List children = element.getChildren();' is inherently broken.
Furthermore with your declaration of Tree<N extends Node<?>>, you would expect that you can write something like List<Node<?>> l2 = element.getChildren();. Unfortunately this does not work due to some subleteties of generics. For example if you change your code to class Tree<N extends Node<N>> (this is probably not what you intended) you can write List<Node<N>> l2 = element.getChildren();.
I recommend to study the Sun Certified Java Programmer Study Guide for Java 6 (or a newer version) or something similar which is really helpful about generics.
From your code I got the impression that you mix different abstraction layers as there is the T data in the Node<T> class and in the for each loop the element is called N data. However in the loop you have a node N extends Node<?> which would be completely different from the T data. Hence the intention for your code remains a bit unclear for me. A working draft if your code as fixed version is here (Eclipse Luna, JDK 6)
package generics.tree;
import java.util.ArrayList;
import java.util.List;
class Tree<T> {
public Node<T> rootElement;
public List<Node<T>> toList() {
List<Node<T>> list = new ArrayList<Node<T>>();
walk(rootElement, list);
return list;
}
private void walk(Node<T> element, List<Node<T>> list) {
list.add(element);
List<Node<T>> children = element.getChildren(); // (1) Cannot convert from List<Node<T>> to List<T>
for (Node<T> data : children) {
walk(data, list);
}
}
}
class Node<T> {
public T data;
public List<Node<T>> children;
public List<Node<T>> getChildren() {
if (this.children == null) {
return new ArrayList<Node<T>>();
}
return this.children;
}
public void addChild(Node<T> child) {
if (children == null) {
children = new ArrayList<Node<T>>();
}
children.add(child);
}
}
class DomainTree extends Tree<String> {
public void build() {
for (Node<String> node : toList()) { // changed!
// process...
}
}
}
class DomainNode extends Node<String> {
}
I have the following design:
I have an Abstract class Instance,
I have a class Library that extends Instance and
I have a class File that also extends Instance
I've created my own linked list implementation and it's defined as follows:
public class List<T extends Instance> implements Iterable {
//some other code here
public Iterator iterator(){
return new ListIterator(this);
}
now I've created a class
public class ListIterator<T extends Instance> implements Iterator<T> {
private List thisList;
private Node current;
public ListIterator(List l){
thisList=l;
current=thisList.head.next;
}
#Override
public boolean hasNext() {
if(current==null)
return false;
return false;
}
#Override
public T next() {
Node temp=current;
current=current.next;
return temp.data;
}
}
Where Node is
public class Node<T extends Instance> {
public Node<T> next;
public Node<T> prev;
public T data;
public Node(T data,Node prev, Node next){
this.data=data;
this.prev=prev;
this.next=next;
}
}
so my problem is as follows: the line return temp.data rises an error:
Type mismatch - cannot convert from Instance to T.
What is wrong with this code?
I'd say that Node.data is a reference to an Instance object? If that is the case, the compiler can't automatically change an Instance to a T, because even though T is an Instance object (T extends Instance), any given Instance might not be a T.
The Java Generics tutorial explains it: http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html
Also, in your List<T> class, you should be specifying Iterator and ListIterator as generic using Iterator<T> and ListIterator<T>, or else the compiler won't be able to handle the generics properly. Your Node reference also needs to be generic: Node<T>
Hence you should be using
private Node<T> current;
and
public T next() {
Node<T> temp=current;
current=current.next;
return temp.data;
}
The compiler will usually warn you when you're using a raw type for a generic class.
Did no one notice the bug:
public boolean hasNext() {
if(current==null)
return false;
return false;
}
This is an invariant. Unless I am missing something, the iterator will very quickly return 0 elements!
What I am trying to do isn't easy; I do realize that. But I would think there is some better way that what I cooked up. Here's the Problem: I am trying to write a generic class to render a Tree that stores Nodes which are evaluable - for example, a Node could be storing a value and just evaluating to that value, or it could be generating a random value, or be an operation on a number of other Nodes - hence I say tree, but the truth is that the internal state of the Node is unknown (for example, a Node may have 0,1,2 or more Node fields for the Children, or an ArrayList of children etc). Of course this wouldn't be an issue if each Node knew how to render itself, but I am trying to avoid this. (Ideally, I would like to be able to render the Tree to a String or as an OpenGL graphic or whatever just by changing the Renderer). Oh and please don't ask questions like "What good would that be?" because I'm just doing this because it seemed interesting.
(By now I figured that I could at least give Nodes the knowledge that they CAN be rendered, and the ability to decide the logical structure of the rendering, but this probably wouldn't improve this too much)
This is what I have so far:
An interface for the Nodes
public interface Node<T> {
T evaluate();
}
A class for value nodes:
public class ValueNode<T> implements Node<T> {
private T value;
#Override
public T evaluate() {
return value;
}
public ValueNode(T value) {
this.value = value;
}
}
A general class for binary operators:
public abstract class BinaryOperator<A, B, T> implements Node<T> {
private Node<A> left;
private Node<B> right;
public BinaryOperator(Node<A> left, Node<B> right) {
this.left = left;
this.right = right;
}
public Node<A> getLeft() {
return left;
}
public Node<B> getRight() {
return right;
}
}
A class for Integer addition:
/**
* I couldn't figure out a generic way to add 2 numbers,
* so I'm going with just Integer for now.
*
*/
public class IntegerAdditionNode extends BinaryOperator<Integer, Integer, Integer> {
public IntegerAdditionNode (Node<Integer> left, Node<Integer> right) {
super(left,right);
}
public Integer evaluate() {
return getLeft().evaluate() + getRight().evaluate();
}
}
And finally, an example string renderer class that allows for new rendering options to be added dynamically. It's extremely ugly though, and I would really appreciate ideas or just a light push in the right direction how I could do this one better:
import java.util.HashMap;
public class NodeToString {
public interface RenderMethod {
public <T extends Node<?>> String renderNode(T node);
}
public static void main(String[] args) {
//test
NodeToString renderer = new NodeToString();
RenderMethod addRender = new RenderMethod() {
private NodeToString render;
public RenderMethod addNodeToString(NodeToString render) {
this.render = render;
return this;
}
#Override
public <T extends Node<?>> String renderNode(T node) {
IntegerAdditionNode addNode = (IntegerAdditionNode) node;
return render.render(addNode.getLeft()) +"+"+render.render(addNode.getRight());
}
}.addNodeToString(renderer);
renderer.addRenderMethod(IntegerAdditionNode.class, addRender);
RenderMethod valueRender = new RenderMethod () {
#Override
public <T extends Node<?>> String renderNode(T node) {
return ((ValueNode<?>)node).evaluate().toString();
}
};
//I don't know why I have to cast here. But it doesn't compile
//if I don't.
renderer.addRenderMethod((Class<? extends Node<?>>) ValueNode.class,
valueRender);
Node<Integer> node = new IntegerAdditionNode(new ValueNode<Integer>(2),
new ValueNode<Integer>(3));
System.out.println(renderer.render(node));
}
private HashMap<Class<? extends Node<?>>, RenderMethod> renderMethods = new
HashMap<Class<? extends Node<?>>, NodeToString.RenderMethod>();
/**
* Renders a Node
* #param node
* #return
*/
public <T extends Node<?>> String render(T node) {
Class nodeType = node.getClass();
if(renderMethods.containsKey(nodeType)) {
return renderMethods.get(nodeType).renderNode(node);
} else {
throw new RuntimeException("Unknown Node Type");
}
}
/**
* This adds a rendering Method for a specific Node type to the Renderer
* #param nodeType
* #param method
*/
public void addRenderMethod(Class<? extends Node<?>> nodeType, RenderMethod method) {
renderMethods.put(nodeType, method);
}
}
I know you say that you are "trying to avoid this" but I really think the Node should have a render() method on it. If you don't want the render code to be in each node type then you could do something like:
public class ValueNode<T> implements Node<T> {
private static RenderMethod rendorMethod;
public static void setRendorMethod(RenderMethod rendorMethod) {
ValueNode.rendorMethod = rendorMethod;
}
...
public String render() {
rendorMethod(this);
}
The way you are doing it will work although I found it unnecessarily complicated. Some comments:
renderer.addRenderMethod(IntegerAdditionNode.class, addRender)
Calling addRenderMethod with a value of addRender took me a while to understand for obvious reasons since add has multiple meanings here. Maybe using the verb put which matched the Map is better.
Calling NodeToString.render() from within your addRender() was confusing although I understand the need.
Method is an overloaded term in Java which makes RenderMethod seem like a Java method not a way of rendering. How about NodeRenderer or just Renderer?
Assigning NodeString to the variable renderer just is strange. It is very different from an addRender or valueRender since it is not a RenderMethod. Maybe it should be?
In all main classes, the first thing I do in the main method is to do something like the following. This makes it less complicated for me at least:
public static void main(String[] args) {
new NodeString().doMain(args);
}
private void doMain(String[] args) {
...
I need to write a tree class in Java where each level has a unique object type. The way it is written below does not take advantage of generics and causes alot of duplicate code. Is there a way to write this with Generics ?
public class NodeB {
private String nodeValue;
//private List<NodeB> childNodes;
// constructors
// getters/setters
}
public class NodeA {
private String value;
private List<NodeB> childNodes;
// constructors
// getters/setters
}
public class Tree {
private String value;
private List<NodeA> childNodes;
// constructors
// tree methods
}
This is simplistic implementation, but enough to give general idea:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GenericNode {
public static abstract class AbstractNode<V, N> {
private V value;
private List<N> children;
public AbstractNode(V value, N... children) {
this.value = value;
this.children = children != null ? Arrays.asList(children)
: Collections.<N> emptyList();
}
public V getValue() {
return value;
}
public List<N> getChildren() {
return children;
}
public int getNumberOfChildren() {
return children.size();
}
#Override
public String toString() {
return value.toString() + "->" + children.toString();
}
}
// leaf node type, ignore type of children
public static class NodeB extends AbstractNode<String, Object> {
public NodeB(String value, Object... nodes) {
super(value, nodes);
}
}
// example of typical node in the mid of tree
public static class NodeA extends AbstractNode<String, NodeB> {
public NodeA(String value, NodeB... nodes) {
super(value, nodes);
}
}
// top level node type
public static class Tree extends AbstractNode<String, NodeA> {
public Tree(String value, NodeA... nodes) {
super(value, nodes);
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <V, N extends AbstractNode> int getNodeCount(
AbstractNode<V, N> node) {
int nodeCount = node.getChildren().size();
for (N child : node.getChildren()) {
nodeCount += getNodeCount(child);
}
return nodeCount;
}
public static void main(String[] args) {
NodeB nodeB1 = new NodeB("Leaf node 1");
NodeB nodeB2 = new NodeB("Leaf node 2");
NodeA nodeA = new NodeA("Node with children", nodeB1, nodeB2);
NodeA emptyNodeA = new NodeA("Empty node");
Tree tree = new Tree("Tree", nodeA, emptyNodeA);
System.out.println(tree);
System.out.println(1 + getNodeCount(tree));
}
}
You could make N and V types implement specific interfaces so it will be possible to call some common operations on values and/or children.
EDIT: updated implementation with recursive method for node count retrieval
All you need is a Pair<A, B>. Example of trees:
Pair<A, Pair<B, C>>
Pair<Pair<A, B>, Pair<C, D>>
Pair<Pair<Pair<A, B>, Pair<C, D>>, Pair<Pair<E, F>, Pair<G, H>>
ps: don't do this. :)
This is an ideal spot for everything inheriting from "Node", but even that is unnecessary.\
What you probably want is a single generic "Node" object that contains references to your different classes (use composition before inheritance).
At that point, each of your different classes probably has something that can be done to them (otherwise why are they all in the same data structure?) Have them implement a common interface with this common functionality. The node class can delegate to this interface, or some other class can extract the class by this interface and act on it.
This would be better than trying to force something to also BE a node--do one simple thing and do it well.
--edit--
I can't really add an example that is relevant to you because you didn't post anything about your scenario.
But let's say that you have these different classes A, B * C. First of all are they related AT ALL aside from all being children of Object? Let's say they all implement interface "Iface". (If not, you can just replace Iface with "Object", but this really implies a bad design.)
Anyway, your "Node" object is just one object--
public class Node {
private List<node> children;
private Iface myObject;
... setters, getters, tree implementation, tree navigation, related garbage...
}
Now this is enough to create your tree. One thing that you might be able to do to make things smoother, have "Node implements Iface" and delegate any calls to it's object. For instance, if Iface contains an eat(Food foodtype) method, your node could implement Iface and have a method:
public void eat(Food foodtype) {
myObject.eat(foodtype);
}
This would make the "Node" class act as though it was the class it contained.
By the way--another relatively good idea at this point would be to make myObject "private final" and ensure it is not null in the constructor. That way you would always know it was set and none of your delegated members would have to do null checks.
I don't think generics are going to help you much in this case. Instead of having a different class for each level in the tree. What about one node class that has children and store a different class on each level. That should help eliminate a lot of the duplication.
I'm fairly new to Java, so this might have issues I'm not aware of, but it seems to work on a simple level at least.
Define your main Node class - this one will be the root of the tree.
public class NodeA {
private String _value;
private ArrayList<NodeA> _children;
private int _depth;
public NodeA (String value, int depth) {
_value = value;
_children = new ArrayList<NodeA>();
_depth = depth;
}
//probably want getters for _children and _value here
//this makes a new child, with its type depending on the depth of the tree it will
//be placed at. NodeB and NodeC will both inherit from NodeA
public void add(String value) {
switch (_depth) {
case 0:
_children.add(new NodeB(value, _depth+1));
break;
case 1:
_children.add(new NodeC(value, _depth+1));
break;
}
}
The add() method is going to create a new child for the node using the specified value. If you initialize the root of the tree as a NodeA with depth 0, you can add children to nodes and the tree should end up populated so that the next level contains all NodeB's, and the next all NodeC's. The code for NodeB and NodeC is super simple and could be replicated to create an arbitrary amount of Node levels (here is that code).
public class NodeB extends NodeA {
public NodeB(String value, int depth) {
super(value, depth);
}
//nothing else needed!
The code for NodeC is identical, except for the obvious replacements of B's with C's.
Hope this helps / is the kind of answer you wanted!