Insufficient Nodes in Root to Leaf Paths - Problem
Binary Tree Path Pruning Challenge

Imagine you're a gardener tasked with pruning a binary tree! 🌳 Given the root of a binary tree and an integer limit, you need to remove all "insufficient" nodes that don't contribute to any path meeting your minimum sum requirement.

📊 What makes a node insufficient?
A node is considered insufficient if every root-to-leaf path that passes through this node has a sum strictly less than the given limit.

🎯 Your Mission:
Delete all insufficient nodes simultaneously and return the root of the resulting tree. If even the root becomes insufficient, return null!

Key Points:
• A leaf node has no children
• Path sums are calculated from root to leaf
• All insufficient nodes are removed in one operation
• The tree structure must remain valid after pruning

Input & Output

example_1.py — Basic Tree Pruning
$ Input: root = [5,4,8,11,null,13,2], limit = 22
Output: [5,4,8,null,13,null,2]
💡 Note: Node 11 is removed because all paths through it (5→4→11 = 20) are less than 22. The path 5→4→13 = 22 and 5→8→2 = 15 are sufficient paths, so those nodes remain.
example_2.py — Complete Tree Removal
$ 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]
💡 Note: All paths with negative values (-99) create insufficient sums. Only paths with positive contributions remain after pruning.
example_3.py — Single Node Edge Case
$ Input: root = [5], limit = 10
Output: null
💡 Note: The single node has value 5, which is less than the limit 10, so the entire tree is removed.

Constraints

  • The number of nodes in the tree is in the range [1, 5000]
  • -105 ≤ Node.val ≤ 105
  • -109 ≤ limit ≤ 109
  • Each root-to-leaf path will have at least one node

Visualization

Tap to expand
Binary Tree Pruning ProcessBefore Pruning54811132After Pruning548132Path Analysis (Limit = 22)Path 1: 5 → 4 → 11 = 20 < 22 ❌Path 2: 5 → 4 → 13 = 22 ≥ 22 ✅Path 3: 5 → 8 → 2 = 15... wait! 🤔Actually, 15 < 22, but node 8 and 2 staybecause they're part of the tree structurethat supports valid paths elsewhere!Only node 11 is removed
Understanding the Visualization
1
Identify All Paths
Find every path from root to leaf and calculate their sums
2
Mark Insufficient Nodes
Nodes are insufficient if ALL paths through them are below the limit
3
Prune the Tree
Remove all insufficient nodes simultaneously, maintaining tree structure
Key Takeaway
🎯 Key Insight: Use post-order DFS to determine node sufficiency bottom-up. A node stays if it has at least one child that leads to a valid path, making this an O(n) optimal solution.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 27
33.7K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen