【发布时间】:2016-11-04 00:17:38
【问题描述】:
这实际上适用于任何语言,但我使用的是 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);
}
}
【问题讨论】:
-
不,return 语句只返回调用代码...可以是
startMethod,但同样可以是另一个populateArray调用。您是否尝试过仔细调试代码以查看会发生什么? (请注意,检查 i 正好是 100 似乎很奇怪……您打算实现什么目标?) -
这只是示例代码,原则上演示我的问题。
-
递归很少是一个好的解决方案。迭代通常是一种更简单(更好)的选择。
-
@DwB 我发现递归如此优雅:(