从递归函数早期返回值

时间:2015-07-16 02:02:18

标签: java recursion

我有一个节点树。在首先迭代此树深度时,我需要将所有重复节点的列表从根节点返回到当前节点。

由于某些业务需求,树的“已遍历”部分永远不会相同。我在已经遍历的树的部分中进行了大量的分支交换/替换。因此,维护遍历节点列表可能不起作用,因为每次遍历节点时都需要更新。

因此,每当我需要回答getDuplicateNodesOfMyCurrentNode()时,我需要从树的顶部开始(rootNode)并深入搜索我的currentNode并返回{{1}这与我的list<Nodes>重复。

currentNode

}

正如你们已经知道这段代码的问题一样,return不会将控件返回给这个API的调用者,因为它递归调用自身。 一旦我到达private void getDuplicateNodesOfMyCurrentNode(Node parentNode, Node currentNode,List<Node> dupNodes){ for(Node child: parentNode.getChildren()){ if(child == currentNode){ return; } if(child.getApp().equals(currentNode.getApp()){ dupNodes.add(child); } getDuplicateNodesOfMyCurrentNode( child, currentNode, aDupNodes); ,我想要一些方法退出这个递归循环。

我可能通过维持一些布尔状态来实现这一点,但想知道解决这个问题的更好方法。

1 个答案:

答案 0 :(得分:2)

通过布尔值传递是否通过调用堆栈中止递归,并在递归调用时放弃当前for循环(同时确认Norbet van Nobelen&#39;上面的评论暗示类似的东西)

private boolean getDuplicateNodesOfMyCurrentNode(Node parentNode, Node currentNode,List<Node> dupNodes){
    for(Node child: parentNode.getChildren()){
        if(child == currentNode){
            return false;
        }
        if(child.getApp().equals(currentNode.getApp()){
            dupNodes.add(child);
        }
        if (getDuplicateNodesOfMyCurrentNode( builtOn, currentNode, aDupNodes) == false){
            return false;
        }
    }
    return true;
}