Insufficient Nodes in Root to Leaf Paths Problem
Description
LeetCode Problem 1080.
Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.
A leaf is a node with no children.
Example 1:

Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
Output: [1,2,3,4,null,null,7,8,9,null,14]
Example 2:

Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
Output: [5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:

Input: root = [1,2,-3,-5,null,4,null], limit = -1
Output: [1,null,-3,4]
Constraints:
- The number of nodes in the tree is in the range
[1, 5000]. -10^5 <= Node.val <= 10^5-10^9 <= limit <= 10^9
Solution
Approach: Post-Order DFS
A node is kept when at least one root-to-leaf path through it reaches limit. That is decided at the leaves and passed upward, so process children before their parent.
Walk down the tree subtracting each node's value from limit. At a node, limit is then what the rest of the path below it still has to add up to.
- Leaf: its path is complete. Keep it if the remaining
limitis<= 0, otherwise delete it (returnnull). - Inner node: first replace its left and right child with the result of the recursive call on them. If both children are now
null, every path through this node was insufficient, so delete it too. Otherwise keep it.
The subtle point is the inner-node rule. Do not compare an inner node's own partial sum with limit: values can be negative, so a path can still go up or down below it, and only leaves have full path sums. Also, an inner node with one child gets deleted when that child is deleted, even though it never was a leaf: the problem asks about paths that existed in the original tree.
Complexity: O(n) time, each node is visited once. O(h) space for the recursion, where h is the height of the tree.
class Solution:
def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:
if root is None:
return None
limit -= root.val # what the rest of the path still has to add up to
if root.left is None and root.right is None:
return None if limit > 0 else root
root.left = self.sufficientSubset(root.left, limit)
root.right = self.sufficientSubset(root.right, limit)
# An inner node survives only if some path through a child is sufficient.
return None if root.left is None and root.right is None else root