我构建了一个由节点组成的树,每个节点都有一个属性和一个后继列表.我试图实现一个递归函数,它开始遍历给定节点的树(在这个例子中,在节点"方法").该函数应计算具有给定属性的嵌套节点的数量.最后,我想返回一个分支中找到的最高编号.说到给定的例子,我想找到具有属性"Loop"的最大嵌套节点数量,该属性为3(相应的分支标记为橙色).
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;
}
Run Code Online (Sandbox Code Playgroud)
这种方法的问题在于它计算给定树中的所有循环,而不是仅仅返回嵌套分支的最大数量.因此,不是返回3(这将是我想要的),而是返回给定示例的7,它等于整个树中"循环"的总数.
显然,我在考虑递归方法时遇到了一些麻烦.有谁能够帮我?