Insufficient Nodes in Root to Leaf Paths - Problem

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.

Input & Output

Example 1 — All paths insufficient
$ Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], limit = 22
Output: []
💡 Note: All root-to-leaf paths (5→4→11→7=27, 5→4→11→2=22, 5→8→13=26, 5→8→4→1=18) have at least one path ≥22, but the node structure requires careful analysis. In this case, all nodes end up being removed.
Example 2 — Some paths sufficient
$ 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: Paths with sum ≥ 1 are kept: 1→2→4→8=15, 1→2→4→9=16, 1→3→7→14=25. Nodes with -99 are removed as they make paths insufficient.
Example 3 — Single node tree
$ Input: root = [5], limit = 10
Output: []
💡 Note: Single node with value 5 < 10, so it's insufficient and removed.

Constraints

  • The number of nodes in the tree is in the range [1, 5000]
  • -105 ≤ Node.val ≤ 105
  • -109 ≤ limit ≤ 109

Visualization

Tap to expand
INPUTALGORITHMRESULT548-3-22Tree with limit = 22Path sums:5+4+(-3) = 65+4+(-2) = 75+8+2 = 151Post-order DFS2Check leaf nodes3Remove insufficient4Propagate upwardAll paths < 22Remove entire treeEmpty TreeAll nodes removedOutput: []No paths meetthe limit requirementKey Insight:Use post-order traversal to check children first, then decide whether to keep parent nodes based on valid paths below.TutorialsPoint - Insufficient Nodes in Root to Leaf Paths | Post-order DFS
Asked in
Amazon 45 Google 32 Microsoft 28 Facebook 25
23.4K Views
Medium Frequency
~25 min Avg. Time
785 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