Problem 915
Insufficient Nodes in Root to Leaf Paths
Medium · 20 pts · Tree, Depth-First Search
Problem
A node is insufficient if every root-to-leaf path passing through it has a sum strictly less than LIMIT. Delete all insufficient nodes at once (a deleted node takes its whole subtree with it) and print the resulting tree, or EMPTY if the root itself is deleted. Recursively, a leaf survives if the path sum to it reaches LIMIT, and an inner node survives exactly when at least one of its children survives after pruning.
Input
The first line contains LIMIT. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children.
Output
Print the tree as level-order tokens separated by spaces, using null for missing children and without trailing nulls, or EMPTY if nothing remains.
Constraints
1 <= number of nodes <= 5000; -10^5 <= value <= 10^5; -10^9 <= LIMIT <= 10^9
Example input
22 13 5 4 8 11 null 17 4 7 1 null null 5 3
Example output
5 4 8 11 null 17 4 7 null null null 5
Explanation
With LIMIT = 22 in 5 4 8 11 null 17 4 7 1 null null 5 3, the paths 5-4-11-1 (21) and 5-8-4-3 (20) are too small, so nodes 1 and 3 are removed while every other node keeps a path of at least 22.