Count Path Sums in an N-ary Tree
A rooted tree has n nodes numbered 0 to n - 1. Node i holds values[i], and parents[i] is its parent; the root is node 0 with parents[0] = -1. A node may have any number of children.
Count the downward paths whose values add up to target. A downward path starts at any node and follows parent-to-child links to any descendant; a single node is a path.
values = [10, 5, -3, 3, 2, 11, 3, -2, 1] parents = [-1, 0, 0, 1, 1, 2, 3, 3, 4] target = 8 answer = 3 // 5 -> 3, 5 -> 2 -> 1, -3 -> 11
Up to 200,000 nodes, values may be negative, and the tree may be a single long chain. Starting a search from every node is too slow, and so is deep recursion.
Hints
Hint 1
For an array, the number of subarrays summing to target comes from prefix sums and a hash map. A root-to-node path is an array.
Hint 2
At a node with running sum S, every ancestor prefix equal to S - target marks the start of a path that ends here.
Hint 3
The map must describe only the current root-to-node path: add the node's prefix when you enter it and remove it when you leave, so siblings do not see each other.
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.