DDSA Solutions

1080. Insufficient Nodes in Root to Leaf Paths

Time: O(n)
Space: O(n)
Advertisement

Intuition

Post-order prune: remove nodes whose entire subtree paths sum < limit. After pruning children, check if current node becomes an insufficient leaf.

Algorithm

  1. 1DFS(node, remaining=limit-node.val).
  2. 2Prune left/right children if they return false (no sufficient path).
  3. 3If both children null: return node.val >= limit (leaf check).
  4. 4Return true if at least one child path is sufficient.

Common Pitfalls

  • Prune bottom-up. A node with both children pruned becomes a leaf and must be rechecked.
1080.cs
C#
// Approach: Post-order DFS; prune a child subtree if its max root-to-leaf sum is below limit; prune the root itself if both children are pruned at a leaf.
// Time: O(n) Space: O(n)

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution
{
    public TreeNode SufficientSubset(TreeNode root, int limit)
    {
        if (root == null)
            return null;

        if (root.left == null && root.right == null)
            return root.val < limit ? null : root;

        root.left = SufficientSubset(root.left, limit - root.val);
        root.right = SufficientSubset(root.right, limit - root.val);

        return root.left == null && root.right == null ? null : root;
    }
}
Advertisement
Was this solution helpful?