1664. Underfunded Branches
A funding plan is a binary tree: each node is a stage with a signed cost value, and a path from the root down to a leaf is a funding route whose total is the sum of all values on it, root and leaf included. A route is underfunded when its total is strictly smaller than limit. Remove every node that lies only on underfunded routes.
Concretely, a leaf survives exactly when its root-to-leaf sum, measured along the original full path, is at least limit, and an internal node survives exactly when at least one of its children survives. Survivors keep their original parent-child links. Return the root of the pruned tree, or an empty tree (null) if nothing survives. Values can be negative, so a partial sum says nothing about the final one. Target O(n) time and O(n) space.
Example 1
- Input:
- root = [8,-2,5,4,null,3,6,-4], limit = 12
- Output:
- [8,null,5,3,6]
- Explanation:
Leaf -4 has route sum 6, below 12, so it is removed and nodes 4 and -2 go with it; leaves 3 and 6 have sums 16 and 19, so they and node 5 survive.
Example 2
- Input:
- root = [3,1,2], limit = 100
- Output:
- []
- Explanation:
The two routes sum to 4 and 5, both below 100, so every node is removed and the result is empty.
Constraints
1 ≤ nodes ≤ 500; -105 ≤ Node.val, limit ≤ 105
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)