1157. Insufficient Nodes in Root to Leaf Paths
My accepted Python solution to LeetCode problem 1157, Insufficient Nodes in Root to Leaf Paths, running in 8ms.
- Difficulty: Medium
- Python
- Runtime 8ms
- Memory 18.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 8ms, memory 18.6MB, accepted 2026-01-02.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:
def dfs(node, current_sum):
if not node:
return None
current_sum += node.val
# If it's a leaf node
if not node.left and not node.right:
# Return None if the path sum is less than limit
if current_sum < limit:
return None
return node
# Recursively process children
node.left = dfs(node.left, current_sum)
node.right = dfs(node.right, current_sum)
# If both children are removed, remove this node too
if not node.left and not node.right:
return None
return node
return dfs(root, 0)