#1080
Insufficient Nodes in Root to Leaf Paths
MediumTreeDepth-First SearchBinary TreeDepth-First SearchTree Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal approach uses a depth-first search (DFS) to calculate the path sum while traversing the tree. Instead of checking all paths after the fact, we can determine if a node is insufficient as we go, allowing us to prune the tree efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Perform a DFS traversal of the tree, keeping track of the current path sum.
- 2Step 2: If a leaf node is reached, check if the path sum is less than the limit.
- 3Step 3: If a node is insufficient, remove it by returning null for that node.
solution.py25 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def sufficientSubset(root, limit):
9 if not root:
10 return None
11 def dfs(node, current_sum):
12 if not node:
13 return current_sum < limit
14 current_sum += node.val
15 if not node.left and not node.right:
16 return current_sum < limit
17 left_insufficient = dfs(node.left, current_sum)
18 right_insufficient = dfs(node.right, current_sum)
19 if left_insufficient:
20 node.left = None
21 if right_insufficient:
22 node.right = None
23 return not node.left and not node.right
24 dfs(root, 0)
25 return root if root.val >= limit else Noneℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Understanding the difference between leaf nodes and internal nodes is crucial for this problem.
- 2Using DFS allows us to efficiently prune the tree while calculating path sums.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.