Write a recursive method listLinks that will list all the links in a tree or sub
ID: 3662571 • Letter: W
Question
Write a recursive method listLinks that will list all the links in a tree or subtree of a node.
The context should be a Node (a class with a getChildren method that will return a List <Node> of the child nodes of that node) and use the toString method of the Node class. The output for each call of the listLinks method should be to System.out, with the first token the representation of the node followed by a space-separated list of the children of the node.
Calling this method in the context of the root node of a tree will result in a listing of all the links in the tree. The call would be something like:
The signature of this method should be:
And you will use a method with the following signature:
Explanation / Answer
void listLinks() {
List<Node> children = getChildren(); // getting children for the current node
System.out.println(this); // printing current node, toString() gets called internally
if (children != null) { // null check
for (int i = 0; i < children.size(); ++i) {
System.out.print(" " + children.get(i)); // printing space separated children
}
for (int i = 0; i < children.size(); ++i) {
children.get(i).listLinks(); // making recursive calls to print all the nodes under current sub-tree
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.