I was given this problem in an interview, while it seemed really easy at first when I got deeper it neraly sound impossible to me with tons of edge cases.
requirments:
Imagine a tree where each node can have from 0 to 10 children, each child has its own weight, write a function that does the following:
- In case the root has no children return -1;
- else, return the sum of the weights of all children of the tree (except the root itself).
I tried something like:
int my_func(node *root) {
if (root->isleaf())
{
return -1;
}
int result = 0;
for (int i = 0; i < root->num_of_children(); ++i)
{
result += my_func(root->child[i]);
}
return result;
}
But this is really bad for 2 reasons:
-
I am not summing weights of all children.
-
when I reach leaf child I am summing -1 while I should add 0.
Aucun commentaire:
Enregistrer un commentaire