
Sponsored
Sponsored
Using 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.
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.
1from typing import List, Optional
2
3class TreeNode:
4 def __init__(self, val=0, left=None, right=None):
5 self.val = val
6 self.left = left
7 self.right = right
8
9class Solution:
10 def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
11 def dfs(node, current_sum, path):
12 if not node:
13 return
14 current_sum += node.val
15 path.append(node.val)
16 if not node.left and not node.right and current_sum == targetSum:
17 result.append(list(path))
18 else:
19 dfs(node.left, current_sum, path)
20 dfs(node.right, current_sum, path)
21 path.pop()
22
23 result = []
24 dfs(root, 0, [])
25 return resultIn this Python solution, we perform a DFS and track the path and its cumulative sum. Upon meeting both the leaf and sum conditions, we add the path to the result using list operations for copying and backtracking.
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.
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.
1#include <vector>
2#include <stack>
3using namespace std;
4
5struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> result;
if (!root) return result;
stack<pair<TreeNode*, pair<int, vector<int>>>> stk;
stk.push({root, {root->val, {root->val}}});
while (!stk.empty()) {
auto [node, state] = stk.top(); stk.pop();
auto [currentSum, path] = state;
if (!node->left && !node->right && currentSum == targetSum) {
result.push_back(path);
}
if (node->right) {
path.push_back(node->right->val);
stk.push({node->right, {currentSum + node->right->val, path}});
path.pop_back();
}
if (node->left) {
path.push_back(node->left->val);
stk.push({node->left, {currentSum + node->left->val, path}});
path.pop_back();
}
}
return result;
}
};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.