-2

I want to count how many leaf node in a trie structure by counting how many words there are in the trie, but my code is not updating the counting value, instead it always reset back to 0.

int num = 0;
public int countLeafNodes() {
    for (char c : children.keySet()) {
        Trie node = children.get(c);
        System.out.println(c);
        if (node.isWord) {
            num++;
            System.out.println(num);
        }
        node.countLeafNodes();
    }
    return num;
    }
thiuye
  • 1
  • 1

2 Answers2

0

You are ignoring the value returned by the recursive call (node.countLeafNodes()).

Try :

public int countLeafNodes() 
{
    int num = 0;
    for (char c : children.keySet()) {
        Trie node = children.get(c);
        System.out.println(c);
        if (node.isWord) {
            num++;
            System.out.println(num);
        }
        num += node.countLeafNodes();
    }
    return num;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Also if there are no children return 1 since that node is a leaf. – apokryfos May 07 '18 at 05:45
  • @apokryfos actually, on second thought, I don't think this is required. When you process the parent of a leaf node, you will check for all the children of that parent (which include that leaf node) `if (node.isWord)` and increment the count. Therefore `node.countLeafNodes()` should return 0 for leaf nodes. – Eran May 07 '18 at 05:52
0

So it appears that the issue is that when you return from your recursion you are not taking in to account the values being returned. What I mean is that when counting the leaf nodes in the children you are not adding that total to the parents. If that is the issue you would just need to change

node.countLeafNodes();  

to

num += node.countLeafNodes();