The format of the input edges does not make it obvious which node is parent and which is child, as the edge may go either way. (There are examples of both ways in the given sample.) So the
set<int> neighbours includes the parent of each node. This is not needed in the subtree sum so must be excluded. That is the purpose of
parents.insert( c ).second
. The insert function returns an {iterator,boolean} pair. If the boolean is false then the insert failed because the set already contains node c (because it is higher up the tree; i.e. the parent). You only need to sum over the subtrees of the children.
Pen72 wrote: |
---|
it shows a few wrong test cases |
That's not particularly helpful information when it comes to debugging.
- what test data causes it to fail (and why)?
- does it fail all, most, or just one or two?
- does it give wrong answer, crash or blow the stack?
- did you have to amend the code in order to apply it in your tester?
Please state the whole problem - including any restrictions on the number of nodes and their values.
In case of overflowing an int variable you could try simply changing
int sumSubTree = 0;
to
long long sumSubTree = 0;
and see if that improves things. If the recursion is so extensive as to blow the call stack then one would need a rethink as to how to store the tree and compute the subtree sums.
A more complex tree has input file (you can redirect standard input):
13
10 20 30 40 50 60 70 80 90 100 110 120 130
1 4
13 1
4 6
4 8
11 4
13 12
2 12
12 10
13 3
12 9
7 3
1 5 |
This still gives the correct answer
910 20 100 290 50 60 70 80 90 100 110 330 560 |