I need to find a solution for this problem: I have a n-ary tree structured in this way:
struct kTreeVertex {
int key;
struct kTreeVertex* child;
struct kTreeVertex* sibling;
};
typedef struct kTreeVertex* kTree;
I can't use another implementation of n-ary tree. My goal is to print for each level the sum of nodes. My function take the pointer to the root of my n-ary tree. The n-ary tree passed to my function is not empty (not null) by pre-condition.
sumLevels(kTree t)
I can't find a way to complete this exercise. Below my solution, but it's not correct.
int sumLevels(kTree t){
if(t->child == NULL){
return t->key;
}
else{
int sum = t->key;
kTree c = t->child->sibling;
while(c != NULL){
sum += sumLevels(c);
c = c->sibling;
}
printf("%d\n", sum);
}
}
if I have this tree:
10
5
8
3
2
1
7
solution should be:
level 0: 10
level 1: 17
level 2: 9
Any ideas?