Reputation: 57
I have a question. If the task is to write down a recursive method,is it ok to create another recursive method that will be called in the original method,would it be considered as a recursive method?
Upvotes: 0
Views: 55
Reputation: 361555
Yes, that's fine, and in fact it is a common pattern. Sometimes you need to do some initial setup before you can begin recursing and therefore need a public method which does the setup and a helper method which does the actual recursion.
For example, to display a tree with levels of indentation:
Setup
public void printTree(Node tree) {
// Setup: Start with 0 indentation.
printNode(tree, 0);
}
Helper
private void printNode(Node node, int spaces) {
// Print the current node.
for (int i = 0; i < spaces; ++i) {
System.out.print(" ");
}
System.out.printf("- %s%n", node.getValue());
// Recursive calls: print the children indented 4 extra spaces.
for (Node child: node.getChildren()) {
printNode(node, spaces + 4);
}
}
Upvotes: 2