-
Notifications
You must be signed in to change notification settings - Fork 0
/
113. Path Sum II
98 lines (84 loc) · 2.83 KB
/
113. Path Sum II
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* 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>> ans;
void helper(TreeNode* root, int s, int const& target, vector<int> tmp) {
s += root->val;
tmp.push_back(root->val);
if(not root->left and not root->right) {
if(s == target)
ans.push_back(tmp);
return;
}
if(root->left) helper(root->left, s, target, tmp);
if(root->right) helper(root->right, s, target, tmp);
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(not root)
return {};
helper(root, 0, targetSum, {});
return ans;
}
};
/**
* 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>> ans;
void helper(TreeNode* root, int const& tar, int s, vector<int> tmp) {
if(not root) return;
if(not root->left and not root->right) {
if(s + root->val == tar) {
tmp.push_back(root->val);
ans.push_back(tmp);
}
return;
}
tmp.push_back(root->val);
helper(root->left, tar, s + root->val, tmp);
helper(root->right, tar, s + root->val, tmp);
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
helper(root, targetSum, 0, {});
return ans;
}
};
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
self.ans = []
def helper(root, s, targetSum, tmp):
if(not root):
return
if(not root.left and not root.right and s + root.val == targetSum):
tmp.append(root.val)
self.ans.append(tmp)
return
helper(root.left, s + root.val, targetSum, tmp + [root.val])
helper(root.right, s + root.val, targetSum, tmp + [root.val])
helper(root, 0, targetSum, [])
return self.ans