#437

Path Sum III

Medium
TreeDepth-First SearchBinary TreeHash MapDepth-First Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

This approach uses a HashMap to store the cumulative sums encountered so far. By keeping track of how many times each cumulative sum has been seen, we can efficiently determine how many paths sum to targetSum as we traverse the tree.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a HashMap to store the cumulative sum counts and set the initial cumulative sum to zero.
  2. 2Step 2: Perform a depth-first search (DFS) through the tree, updating the cumulative sum at each node.
  3. 3Step 3: For each node, check if (cumulative sum - targetSum) exists in the HashMap. If it does, it means there are paths that sum to targetSum.
  4. 4Step 4: Update the HashMap with the current cumulative sum count before moving to the next node.
  5. 5Step 5: After visiting the node's children, decrement the count of the current cumulative sum in the HashMap to backtrack.
solution.py24 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
8class Solution:
9    def pathSum(self, root: TreeNode, targetSum: int) -> int:
10        self.count = 0
11        self.cumulative_sum_counts = {0: 1}
12        self.dfs(root, 0, targetSum)
13        return self.count
14
15    def dfs(self, node: TreeNode, current_sum: int, targetSum: int):
16        if not node:
17            return
18        current_sum += node.val
19        self.count += self.cumulative_sum_counts.get(current_sum - targetSum, 0)
20        self.cumulative_sum_counts[current_sum] = self.cumulative_sum_counts.get(current_sum, 0) + 1
21        self.dfs(node.left, current_sum, targetSum)
22        self.dfs(node.right, current_sum, targetSum)
23        self.cumulative_sum_counts[current_sum] -= 1
24

Complexity note: The time complexity is O(n) because we visit each node once, and the space complexity is O(n) due to the storage of cumulative sums in the HashMap.

  • 1Paths can start and end at any node, not just root or leaves.
  • 2Using cumulative sums allows us to efficiently track paths without recalculating sums repeatedly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.