Equalize Root-to-Leaf Sums in an N-ary Tree
Company: ByteDance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Overview: Find the minimum total increments needed to make every root-to-leaf path in a nonnegative-valued N-ary tree have the same sum. The parent-array input may contain 200,000 nodes and a depth beyond Python's recursion limit.
Constraints
- 1 <= len(values) == len(parents) <= 200,000
- 0 <= values[i] <= 10^9
- parents[0] == -1 and the parent array describes one valid rooted tree.
- A node may have any number of children.
- Use an iterative traversal so very deep trees are supported.
- Return the exact count as a canonical decimal string with no leading zeroes.
Examples
Input: ([5], [-1])
Expected Output: "0"
Explanation: One root-to-leaf path is already equal to itself.
Input: ([2, 3, 4], [-1, 0, 0])
Expected Output: "1"
Explanation: Raise the lower child by one.
Hints
- Process children before their parent with an explicit-stack postorder.
- For each child subtree, keep its already-equal root-to-leaf sum and accumulate the operation count with arbitrary-precision or decimal arithmetic.
- Sibling subtree sums must all be raised to their maximum; increasing a child root raises every path in that child subtree together.