Leetcode 113: Path Sum II

grid47
grid47
Exploring patterns and algorithms
Oct 26, 2024 6 min read

A radiant path of numbers, showing multiple possible paths with gentle branches leading to different sums.
Solution to LeetCode 113: Path Sum II Problem

Given the root of a binary tree and an integer targetSum, return all paths from the root to the leaf nodes where the sum of the node values along the path equals the targetSum. A root-to-leaf path is defined as any path that starts from the root and ends at a leaf node. A leaf node is a node that does not have any children.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary tree represented by the root node and an integer targetSum. The binary tree is represented as an array where each node is given by its value. Null values represent missing nodes.
Example: Input: root = [10,5,15,3,7,null,20], targetSum = 22
Constraints:
• The number of nodes in the tree is in the range [0, 5000].
• Each node value is between -1000 and 1000.
• The targetSum is between -1000 and 1000.
Output: The output should be a list of all root-to-leaf paths, where each path is represented as a list of node values that sum up to the given targetSum.
Example: Output: [[10,5,3], [10,15,20]]
Constraints:
• Each path should be a valid root-to-leaf path with the sum of node values equal to targetSum.
Goal: The goal is to traverse the tree and accumulate the path sum from the root to the leaf nodes. If a path's sum matches the targetSum, it should be added to the result.
Steps:
• Traverse the tree using depth-first search (DFS).
• At each node, subtract its value from targetSum and continue exploring both left and right children.
• If a leaf node is reached and the remaining sum equals 0, add the current path to the result.
Goal: The tree may have up to 5000 nodes, and each node's value can range from -1000 to 1000. The solution should handle these efficiently.
Steps:
• Tree size: 0 <= number of nodes <= 5000
• Node values: -1000 <= Node.val <= 1000
• Target sum: -1000 <= targetSum <= 1000
Assumptions:
• The input tree is a valid binary tree, where nodes have either zero, one, or two children.
Input: Input: root = [10,5,15,3,7,null,20], targetSum = 22
Explanation: Starting from the root (10), we explore the left child (5) and its left child (3), which gives the path [10,5,3] with sum 22. We also explore the right child (15) and its right child (20), which gives the path [10,15,20] with sum 22.

Input: Input: root = [1,2,3], targetSum = 5
Explanation: No path from root to leaf sums up to 5. Therefore, the output is an empty list.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus