-
Notifications
You must be signed in to change notification settings - Fork 1
Recursion
When the problem we're trying to solve is so small, we already know the answer and there's nothing left to do. We do not call the method recursively in the base case.
- Take care of the current value
- Recursively call the method to solve a slightly smaller version of the same problem... may involve a "recursive leap of faith"
The stack takes up space in the computer. Recursion increases the stack space, in terms of stack frames, so this can be a downside. If you have a horribly long linked list, you can get a stack overflow in recursion.
When doing linked lists and recursion, you write your recursive methods to take in and return the nodes, not the list itself.
When dealing with lots of pointers in the code, especially when there are temps in the code, consider recursion!
A -> B -> C -> D
1 + (length of the rest of the list)
Find the length of the rest of the list first - think of this as the .next part. Then, add in the base case.
int recursiveLength (Node n) {
if (n == null) {
return 0;
}
recursiveLength(n.next) + 1;
}
or, write it more broken up:
int recursiveLength (Node n) {
if (n == null) {
return 0;
}
int lengthOfThisNode = 1;
int lengthOfTheRestOfTheNodes = recursiveLength(n.next);
return lengthOfThisNode + lengthOfTheRestOfTheNodes;
}
int recursiveSum (Node n) {
if (n == null) {
return 0;
}
int sumOfThisNode = n.value;
int sumOfRestOfNodes = recursiveSum (n.next)
return sumOfThisNode + sumOfRestOfNodes'
}
or, just...
int recursiveSum (Node n) {
if (n == null) {
return 0;
}
return n.value + sum(n.next);
https://github.com/codefellows/seattle-java-401d6/tree/master/class-09
Demo code based on counting the number of leaves in a tree from class 19 of Java-401d6. Java-401d6 video
https://github.com/SharinaS/java-fundamentals/wiki/Trees
FrontRow from October 30, 2019, Code Review of TreeIntersection Code Challenge
TreeIntersection Code Challenge