[LeetCode] Path Sum II

113. Path Sum II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Definition for a binary tree node.
* struct 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 {
vector<vector<int>> res;
void helper(TreeNode* node, int target, vector<int>& A) {
if(!node->left and !node->right) {
if(target == node->val) {
res.push_back(A);
res.back().push_back(target);
}
return;
}

target -= node->val;
A.push_back(node->val);

if(node->left)
helper(node->left, target, A);
if(node->right)
helper(node->right, target, A);

A.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root) helper(root, targetSum, vector<int>() = {});
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/16/PS/LeetCode/path-sum-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.