Make the Leaf class with the basic information.
Make the Branch class which holds references to Leafs.
Make the Node class which holds references to Brahces.
Then try look up Recursion and how to use it to make such constructs :)
Here is my go at it. Though not very elegant, it gets the job done.
Here is the Leaf class:
public class Leaf {
private String text;
public Leaf(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setString(String newString) {
text = newString;
}
@Override
public String toString() {
return text;
}
}
And here is the Branch class:
public class Branch<T> {
private String text;
private HashSet<T> list;
public Branch(String text) {
this.text = text;
list = new HashSet<>();
}
public String getText() {
return text;
}
public void setText(String newText) {
text = newText;
}
public HashSet<T> getHashSet() {
return list;
}
public void setHashSet(HashSet<T> newList) {
list = newList;
}
public String getAllLeaves() {
StringBuilder sb = new StringBuilder();
sb.append(text).append("\n");
for(T t : list) {
sb.append("\t\t");
sb.append(t.toString()).append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return text;
}
}
Lastly the Node class:
public class Node<T> {
private String text;
private HashSet<T> list;
public Node(String text) {
this.text = text;
list = new HashSet<>();
}
public String getText() {
return text;
}
public void setText(String newText) {
text = newText;
}
public HashSet<T> getHashSet() {
return list;
}
public void setHashSet(HashSet<T> newList) {
list = newList;
}
}
Little test program to try it out:
public class TreeConstruct {
public static void main(String[] args) {
Leaf l1 = new Leaf("Leaf 1");
Leaf l2 = new Leaf("Leaf 2");
Leaf l3 = new Leaf("Leaf 3");
Leaf l4 = new Leaf("Leaf 4");
Branch<Leaf> b1 = new Branch("Branch 1");
Branch<Leaf> b2 = new Branch("Branch 2");
Node<Branch> n1 = new Node("Node 1");
b1.getHashSet().add(l1);
b1.getHashSet().add(l2);
b1.getHashSet().add(l3);
b2.getHashSet().add(l4);
n1.getHashSet().add(b1);
n1.getHashSet().add(b2);
System.out.println(printNodeTree(n1));
}
public static String printNodeTree(Node<Branch> n) {
StringBuilder sb = new StringBuilder();
sb.append(n.getText()).append("\n");
for(Branch b : n.getHashSet()) {
sb.append("\t");
sb.append(b.getAllLeaves());
}
return sb.toString();
}
}
The output will be:
Node 1
Branch 1
Leaf 1
Leaf 3
Leaf 2
Branch 2
Leaf 4
Hope this helps!