Advertisement

Path Sum - LeetCode 112 Solution

Path Sum - Complete Solution Guide

Path Sum is LeetCode problem 112, a Easy 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 true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum . A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown. Example 2: Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There are two root-to-leaf paths in the tree: (1 -->

Detailed Explanation

You're handed the root of a binary tree and a specific `targetSum`. Your mission isn't just to find any path that adds up to this sum, but very specifically, a 'root-to-leaf' path. This means starting at the very top of the tree, traversing downwards, and only checking the sum once you've arrived at a node that has no children whatsoever (a true 'leaf'). If even one such path exists, you return `true`; otherwise, `false`.

Solution Approach

The provided solution leverages a classic Depth-First Search (DFS) strategy, which is perfectly suited for exploring every possible root-to-leaf path. It's a recursive journey: we start at the root and pass down the `current_sum` accumulated so far. At each node, we add the node's value to our `current_sum`. The key logic then splits: if we've arrived at a leaf node (meaning it has no left *and* no right child), we check if our `current_sum` now equals the `targetSum`. If it does, we've found our path, and we can immediately return `true`. If it's not a leaf, we continue the journey by recursively calling our `dfs` function on both the left and right children. The `or` operator here is crucial – if *either* the left branch *or* the right branch eventually finds a path, our overall `hasPathSum` function correctly returns `true`, short-circuiting any further exploration.

Step-by-Step Algorithm

  1. Step 1: Check if the root node is null. If it is, return `false` because there are no paths.
  2. Step 2: If the current node is a leaf node (no left and no right children), check if the current sum (accumulated during the traversal) equals the `targetSum`. Return `true` if they are equal, `false` otherwise.
  3. Step 3: Recursively call the function (DFS) for the left and right subtrees. Subtract the current node's value from the `targetSum` before the recursive call. Return `true` if either recursive call returns `true`, indicating a path with the target sum was found; otherwise, return `false`.

Key Insights

  • **Leaf-Node Specific Sum Check:** The `targetSum` comparison is strictly performed *only* when a `node` is confirmed to be a leaf (`not node.left and not node.right`). This precisely adheres to the 'root-to-leaf' requirement and distinguishes it from problems asking for path sums ending at any arbitrary node.
  • **Cumulative Sum through Recursion State:** The `current_sum` isn't a global variable. Instead, it's passed as an argument in each recursive call. This elegant pattern ensures that each branch of the DFS independently maintains its path's sum, naturally 'undoing' parent sums as the call stack unwinds and preventing interference between sibling paths.
  • **Early Exit with Logical `or`:** The `dfs(node.left, current_sum) or dfs(node.right, current_sum)` structure provides an efficient short-circuiting mechanism. As soon as *any* left or right branch finds a valid path summing to `targetSum`, the `or` condition evaluates to `true`, and subsequent explorations (e.g., of the right subtree if the left finds a path) are completely bypassed, optimizing execution time.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(h)

Topics

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

Companies

Asked at: Datadog, PayPal, TikTok.