这可以适用于任何语言,但我使用的是Java。这看起来很简单,但我现在已经编了好几个小时,而且我的脑子已经油炸了,我只是想念一些简单的东西。见下面的例子。在下面的populateArray()
方法中,有一个返回调用(请参阅注释)但会导致父方法过早返回(在所有递归完成并且mListUrls
完全填充之前)?
public ArrayList<String> startMethod( String s){
mString = s;
Node startNode = getNode(mString );
populateArray(startNode, 0 );
return mListValues;
}
private void populateArray(Node node, int i{
if(i == 100 ){
mListValues.add(node.value);
//I do want to continue here, but will returning here return the startMethod() above prematurely,
//before all recursion is completed?
return;
}
if(node.first() != null){
populateArray(node.first(), i + 1);
}
if(node.second() != null){
populateArray(node.second(), i + 1);
}
if(node.third() != null){
populateArray(node.third(), i + 1);
}
}
答案 0 :(得分:0)
当populateArray调用自身,populateArray时,递归就会发挥作用。当任何调用返回时,它只返回其父级,可能是populateArray或其他一些函数。想想一堆电话,任何回报只会弹出顶部。它不会一直返回基地。父母可以决定做什么。它可以决定任何数量的东西,调用别的东西,再次递归,或者返回它的父级(祖父母),它可以很好地级联到根,但不一定。