I built a tree consisting of nodes with each node having an attribute and a list of successors. I am trying to implement a recursive function which starts traversing the tree at a given node (in this example at the node "Method"). The function shall count the number of nested nodes with a given attribute. At the end, I want to return the highest number found within a single branch. Speaking of the given example, I would like to find the maximum amount of nested nodes with the attribute "Loop" which would be 3 (the according branch is marked orange).
Example: Currently, my approach looks like this:
private static int getLNDforMethod(DirectedNodeInterface curNode, int currentLND) {
NodeIterator successors = curNode.getSuccessors();
while(successors.hasNext())
{
successors.next();
DirectedNodeInterface curSuc = (DirectedNodeInterface) successors.getNode();
// isLoop returns true if the given node is a loop
if(isLoop(curSuc))
{
++currentLND;
}
currentLND = getLNDforMethod(curSuc, currentLND);
}
return currentLND;
}
The problem with this approach is that it is counting all loops within a given tree instead of just giving back the maximum number of a nested branch. So instead of returning 3 (which would be what I want) it returns 7 for the given example which equals the total number of "Loops" in the whole tree.
Apparently, I have some trouble thinking into recursive methods. Can anybody help me?
int currentMax = 0
at the start of the method and acurrentMax = Math.max(currentMax,getLND...
in your successors loop. – OldCurmudgeon