1

I m trying to calculate the value of prefixCount in Trie, as below.

I am puzzled why the value of count is not returned as 3

Just in case , Tries contains [by,bye, byer, rat]. Why count is return as 0, and not 3.

public int prefixCount(String prefix)
{
    int count = 0;
    TrieNode node = searchPrefix(prefix);
    if(node != null)
    {
        prefixCount(prefix, node, count);
    }
    return count;
}

public void prefixCount(String prefix, TrieNode node, int count)
{
    if(node.isEnd())
    {
        count++;
    }

    for(int index = 0;index < 26;index++)
    {
        char value = (char) (index + 'a');
        TrieNode next = node.get(value);
        if(next != null)
        {
            prefixCount(prefix + value, next, count);
        }
    }
}

Am i doing something wrong while doing DFS operation.

Thanks !

user1993412
  • 802
  • 2
  • 15
  • 29

1 Answers1

0

I was not defining my method correctly. The appropriate method would be as below.

public int prefixCount(String prefix)
{
    int count = 0;
    TrieNode node = searchPrefix(prefix);
    if(node.isEnd())
    {
        count++;
    }

    for(int index = 0;index < 26;index++)
    {
        char value = (char) (index + 'a');
        TrieNode next = node.get(value);
        if(next != null)
        {
            count += prefixCount(prefix + value);
        }
    }
    return count;
}

Thanks !

user1993412
  • 802
  • 2
  • 15
  • 29