A genealogical registry stores one family lineage as a rooted binary tree, where every person holds an estate value and points to at most two children. A person is called a solo heir when they are not the root and their parent has exactly one child -- meaning that person grew up with no sibling to share the household with. Given the family tree, find the sum of estate values over every solo heir.
n -- the number of people in the lineage.n lines: the i-th of these (0-indexed) describes person i as three integers value left right, where value is that person's estate value, and left/right are the 0-indexed positions of their left/right child in this list, or -1 if that child does not exist. Person 0 is always the root.Print a single integer: the sum of estate values over all solo heirs (people who are not the root and whose parent has exactly one child). If there are no solo heirs, print 0.
1 <= n <= 1000-10000 <= value <= 10000left/right index is either -1 or a valid, distinct node index in 0..n-1. The described structure is always a valid rooted binary tree with no cycles, and node 0 is the root.Example 1
Input
5 1 1 2 2 3 -1 3 -1 4 4 -1 -1 5 -1 -1
Expected
9
Explanation
The root (value 1) has two children: value 2 (node 1) and value 3 (node 2), so neither of them is a solo heir -- they have each other as siblings. Node 1 (value 2) has only a left child, node 3 (value 4), so node 3 is a solo heir. Node 2 (value 3) has only a right child, node 4 (value 5), so node 4 is a solo heir. The sum of solo-heir values is 4 + 5 = 9.
Example 2
Input
1 42 -1 -1
Expected
0
Explanation
The lineage contains only the root. A solo heir must have a parent, and the root has none, so no one qualifies and the sum is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →