简体   繁体   中英

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?

When writing a recursive algorithm, you need a base case... In this case the base case is when your Trie has no children. Here we would expect a length of 1.

The recursive case is held inside your for loop (An internal node). 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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