0

I have to write a function to find the number of nodes in a level of a first child - next sibling N-ary tree. My function is:

int nodesAtLevel(NTree root, int level) {
    if (root == NULL) {
        return 0;
    }
    if (level == 0) {
        return 1;
    }
    return nodesAtLevel(root->firstChild, level - 1) + 
           nodesAtLevel(root->nextSibling, level - 1);
}

but it does not work. Can someone help me?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
J.D.
  • 105
  • 6
  • 1
    *but it does not work* How should it work?How is it not working? – Gaurav Sehgal Jul 27 '17 at 09:47
  • Can you explain why you are decrementing `level` when calculating the number of nodes associated with `nextSibling`? – r3mainer Jul 27 '17 at 09:48
  • The structure of your tree is unclear. This is an n-ary tree? So not only does a node have children it has siblings? And if that's the case, then `if(level == 0) { return 1; }` wouldn't be correct. What if the current level has siblings? The answer would not then be 1. If you haven't done so, draw yourself a picture of the tree structure and use it as a guide to understand your code. – lurker Jul 27 '17 at 10:24

1 Answers1

0

Right now, your code seems to only return 2. I believe this is what you are trying to do:

int nodesAtLevel(NTree root, int level) {
    if (root == NULL) {
        return 0;
    }
    if (level == 0) {
        return 1;
    }

    int x = nodesAtLevel(root->firstChild, level - 1);
    int y = nodesAtLevel(root->nextSibling, level - 1);

    return x + y + 1; //add 1 for current node
}

This should update the value after every recursion, unlike your current code.

mannuscript
  • 4,711
  • 6
  • 26
  • 25
Devin L.
  • 437
  • 2
  • 12