【问题标题】:for loop encounter return statement in recursion methodfor循环在递归方法中遇到return语句
【发布时间】:2015-10-27 11:19:24
【问题描述】:
public void delete(String key) {
    root = delete(root, key, 0);
}

public Node delete(Node x, String key, int d) {
    if(x == null) 
        return null;
    if(d == key.length())
        x.val = null;
    else {
        char c = key.charAt(d);
        x.next[c] = delete(x.next[c], key, d + 1);
    }

    //----------------
    if(x.val !=null ) 
        return x;
    for (char c = 0;c < R ; c++ ) {
        if(x.next[c] != null)
            return x;
        return null;
    }
}

来自书籍算法 4,TrieST.java

那么发生了什么? for循环可以多次返回x;返回类型方法可以吗?如果可以,那么最终的返回值是多少?

【问题讨论】:

  • 这看起来像是一个错字。如果 for 循环总是在第一次迭代中返回,则不需要循环。
  • 错字是什么意思?输入?

标签: java algorithm dictionary trie


【解决方案1】:

一旦调用“return”,函数就会终止。

所以函数返回的值是:

  • x 如果 x.val != null
  • x 如果对于第一个 c(即 c = 0),x.next[c] !=null
  • null 否则

如cmets中所说,我猜肯定有错字

return null;

应该在for循环之后。然后函数会返回:

  • x 如果 x.val != null
  • x 如果存在 x.next[c] !=nullc
  • null 否则

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-17
    • 2014-08-28
    • 1970-01-01
    • 2014-09-30
    • 2012-08-01
    • 2019-10-07
    相关资源
    最近更新 更多