AlgoMaster Logo

Path Sum III

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

The brute force approach involves iterating over each node and trying to find all paths starting from each node that sum up to the given targetSum. For each node, we perform a DFS traversal while counting paths that result in the targetSum.

Steps:

  1. For each node, you calculate path sums starting from the node itself.
  2. Use a helper function to recursively calculate path sums from the current node.
  3. Use another function to iterate over each node and treat it as a starting point.

Code:

2. Prefix Sum Approach

Intuition:

This optimized approach uses a hashmap to store the prefix sum frequencies encountered so far while traversing the tree. The idea is to leverage the prefix sum technique to quickly find if there exists a subpath ending in the current node that sums up to the targetSum.

Steps:

  1. Use a recursive function to traverse the tree.
  2. For each node, calculate its prefix sum.
  3. Use a hashmap to check whether there exists a prefix sum such that removing it from the current prefix sum would give us the targetSum.
  4. Update the prefix sum count in the hashmap while going deeper into the recursion and undo changes when backtracking.

Code: