Hi there,
I have a task to
Create a program that:
-finds the shortest way which connects the root with a leaf in the Tree;
-finds the closest common parent of two given nodes A1 and A2 in the Tree;
-finds all nodes, which are simultaneously parents of nod A1 and children of nod A2 from the Tree;
-puts out on the screen a structure of the Tree,with the root on top.
I wonder how can i convert the printDFS function to display my Tree as in the picture below
FILE Tree.java
import java.util.ArrayList;
public class Tree<Type> {
public static class TreeNode<Type> {
private Type value;
private boolean hasParent;
private ArrayList<TreeNode<Type>> children;
public TreeNode(Type value) {
if (value == null) {
throw new IllegalArgumentException("Cannot insert null value!");
}
this.value = value;
this.children = new ArrayList<TreeNode<Type>>();
}
public Type getValue() {
return this.value;
}
public void setValue(Type value) {
this.value = value;
}
public void addChild(TreeNode<Type> child) {
if (child == null) {
throw new IllegalArgumentException("Cannot insert null value!");
}
if (child.hasParent) {
throw new IllegalArgumentException(
"The node already has a parent!");
}
child.hasParent = true;
this.children.add(child);
}
public TreeNode<Type> getChild(int index) {
return this.children.get(index);
}
public int getChildrenCount() {
return this.children.size();
}
}
private TreeNode<Type> root;
public Tree(Type value) {
if (value == null) {
throw new IllegalArgumentException("Cannot insert null value!");
}
this.root = new TreeNode<Type>(value);
}
public Tree(Type value, Tree<Type>... children) {
this(value);
for (Tree<Type> child : children) {
this.root.addChild(child.root);
}
}
public TreeNode<Type> getRoot() {
return this.root;
}
public ArrayList<TreeNode<Type>> getChildNodes() {
if (this.root != null) {
return this.root.children;
}
return new ArrayList<TreeNode<Type>>();
}
private void printDFS(TreeNode<Type> root, String spaces) {
if (this.root == null) {
return;
}
System.out.println(spaces + root.getValue());
TreeNode<Type> child = null;
for (int i = 0; i < root.getChildrenCount(); i++) {
child = root.getChild(i);
printDFS(child, spaces + " ");
}
}
public void printDFS() {
this.printDFS(this.root, new String());
}
}
FILE TreeExample.java
public class TreeExample {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Tree<Integer> tree =
new Tree<Integer>(7,
new Tree<Integer>(5,
new Tree<Integer>(5),
new Tree<Integer>(5)),
new Tree<Integer>(19,
new Tree<Integer>(1),
new Tree<Integer>(12),
new Tree<Integer>(31)),
new Tree<Integer>(21),
new Tree<Integer>(14,
new Tree<Integer>(23),
new Tree<Integer>(6))
);
tree.printDFS();
}
}
MY CURRENT DISPLAY OF THE TREE IS:
7
5
5
5
19
1
12
31
21
14
23
6