Loading...
Loading...
The cultural fest committee is organised as a tree. Each coordinator has at most two members under them. Members with no one under them are the leaves: they sold tickets and report a net amount in rupees. A negative amount means they spent more than they collected.
Print the total of the amounts reported by the leaves only. An empty committee reports 0.
N for no node. Children are listed only for real nodes, and N tokens at the end of the line may be left out. For example, 1 2 3 N 4 is root 1 with children 2 and 3, and 4 is the right child of 2. An empty tree is the single token N.Example 1
Input
1 2 3 N 4
Output
7
The leaves are 4 and 3, so the total is 7. Node 2 has a child, so it is not a leaf.
Example 2
Input
-5 3 -8 2 N N -1
Output
1
The leaves are 2 and -1, so the total is 1.
Try the problem first. Open one hint at a time.
A leaf is a node with no left child and no right child.
Visit every node. Add its value only when both children are missing.
A method that returns 0 for a missing node, the value for a leaf, and the sum of both sides otherwise covers every case.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor