Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22
Example 2:
Input: root = [1,2,3], targetSum = 5 Output: []
Example 3:
Input: root = [1,2], targetSum = 0 Output: []
Constraints:
[0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000Using a recursive DFS, traverse each path from root to leaf, maintaining the current path and its corresponding sum. When a leaf is reached, check if the path's sum matches the targetSum. Use backtracking to explore all paths.
We use a helper function, dfs, to recursively explore paths. We store current paths and their sums in arrays to keep track of potential solutions. When a solution is found at a leaf node, it is added to the result set, and backtracking ensures all paths are checked.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N), where N is the number of nodes in the tree.
Space Complexity: O(H), where H is the height of the tree, due to the recursion stack.
An iterative approach using a stack can also be used for this problem. We maintain stacks that parallel traditional DFS traversal with added structures to track path and cumulative sum states for efficient exploration of all feasible root-to-leaf paths.
This C++ solution employs a stack to simulate DFS traversal iteratively. The stack holds node, cumulative sum, and path data. As each node is processed, we check for valid paths and update the result list accordingly. Paths are extended by exploring left and right children, augmented by the current node value.
JavaScript
Time Complexity: O(N), as each node is processed exactly once.
Space Complexity: O(N), since results and stack can store all nodes during worst-case full-tree traversal.
| Approach | Complexity |
|---|---|
| Recursive Depth-First Search | Time Complexity: O(N), where N is the number of nodes in the tree. Space Complexity: O(H), where H is the height of the tree, due to the recursion stack. |
| Iterative Depth-First Search with Stack | Time Complexity: O(N), as each node is processed exactly once. Space Complexity: O(N), since results and stack can store all nodes during worst-case full-tree traversal. |
TWO SUM II - Amazon Coding Interview Question - Leetcode 167 - Python • NeetCode • 460,623 views views
Watch 9 more video solutions →Practice Path Sum II with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor