Advertisement

Path Sum III - LeetCode 437 Solution

Path Sum III - Complete Solution Guide

Path Sum III is LeetCode problem 437, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given the root of a binary tree and an integer targetSum , return the number of paths where the sum of the values along the path equals targetSum . The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). Example 1: Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8 Output: 3 Explanation: The paths that sum to 8 are shown. Example 2: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum =

Detailed Explanation

The problem asks us to find the number of paths in a binary tree where the sum of the node values along the path equals a given `targetSum`. A path can start and end at any node, but it must go downwards (from parent to child). This means we need to consider all possible downward paths within the tree, not just those starting at the root or ending at a leaf.

Solution Approach

The provided solutions utilize a Depth-First Search (DFS) algorithm combined with the concept of prefix sums. The DFS explores each node in the tree. A HashMap (or unordered_map in C++, or HashTable in C) is used to store the counts of different prefix sums encountered along the current path from the root to the current node. For each node, we check if there's a prefix sum encountered earlier such that the difference between the current prefix sum and that earlier prefix sum equals the target sum. If so, it means there's a path ending at the current node that sums to the target. We recursively explore the left and right subtrees, updating the prefix sum count as we go, and then decrementing the count before returning (backtracking) to ensure we only count paths relevant to the current branch. The initial entry in the hash map is 0 with a count of 1, representing an empty path that starts from the root's parent node.

Step-by-Step Algorithm

  1. Step 1: Initialize a HashMap (or unordered_map/HashTable) to store prefix sum counts. Add an initial entry of (0, 1) to represent an empty path from before the root, which makes it possible to find paths starting from the root node itself.
  2. Step 2: Define a recursive DFS function that takes the current node, the current path sum, the target sum, and the prefix sum counts HashMap as input.
  3. Step 3: Base case: If the current node is null, return 0 (no path found).
  4. Step 4: Update the current path sum by adding the value of the current node.
  5. Step 5: Check if there exists a previous path (prefix) sum such that `current_path_sum - targetSum` equals a previously seen prefix sum. If so, it means there is a path ending at the current node with a sum equal to `targetSum`. Add the count of that prefix sum to the total count.
  6. Step 6: Increment the count of the `current_path_sum` in the HashMap.
  7. Step 7: Recursively call the DFS function on the left and right children of the current node, accumulating the counts from each subtree.
  8. Step 8: Before returning from the recursive call, decrement the count of the `current_path_sum` in the HashMap. This is a backtracking step that ensures that the prefix sum counts are only relevant to the current path being explored.
  9. Step 9: Return the total count of paths found.

Key Insights

  • Insight 1: A brute-force approach of checking every possible path would be inefficient. We need a way to optimize the path sum calculation.
  • Insight 2: The use of prefix sums allows us to efficiently determine if a subpath exists with the desired sum. By storing the cumulative sum from the root to each node, we can quickly calculate the sum of any path between two nodes.
  • Insight 3: The path can start at any node, not just the root. Therefore, a recursive approach that explores all possible starting points and downward paths is necessary.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(n)

Topics

This problem involves: Tree, Depth-First Search, Binary Tree.

Companies

Asked at: Flipkart, NetApp, Zepto.