简体   繁体   English

Java 数组 Arrays 长度

[英]Java Array of Arrays length

private class TrieNode<T>{
    private data;
    private TrieNode[] children;
    public TrieNode(){
       data = null;
       children = new TrieNode[26];
    }
    public int getSize(){
       int length = 0;
       for(int i = 0; i < 26; i++){
           if(children[i]!=null){
               length += children[i].getSize()+1;
            }
        }
     return length;
    }


}

Hey can someone please tell me why the getSize method is always giving me one less than it is supposed to?嘿,有人能告诉我为什么 getSize 方法总是给我比它应该的少一个吗?

When writing a recursive algorithm, you need a base case... In this case the base case is when your Trie has no children.编写递归算法时,您需要一个基本情况......在这种情况下,基本情况是您的 Trie 没有孩子。 Here we would expect a length of 1.在这里,我们期望长度为 1。

The recursive case is held inside your for loop (An internal node).递归案例保存在您的 for 循环中(一个内部节点)。 You should not be adding one for each iteration of the loop, this is handled by the base case.您不应该为循环的每次迭代添加一个,这是由基本情况处理的。 Instead you should just be adding the size of each child.相反,您应该只添加每个孩子的大小。

Try the following code...试试下面的代码...

public int getSize() {
    int length = 1;
    for (int i = 0; i < 26; i++ ) {
       if(children[i]!=null) {
          length += children[i].getSize();
       }
    }

    return length;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM