-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathbinary-tree-path-sum.cpp
45 lines (42 loc) · 1.15 KB
/
binary-tree-path-sum.cpp
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
// Time: O(n)
// Space: O(h)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
vector<vector<int>> res;
vector<int> cur;
binaryTreePathHelper(root, target, &cur, &res);
return res;
}
void binaryTreePathHelper(const TreeNode *root, const int target,
vector<int> *cur, vector<vector<int>> *res) {
if (!root) {
return;
}
cur->emplace_back(root->val);
if (!root->left && !root->right && root->val == target) {
res->emplace_back(*cur);
} else {
binaryTreePathHelper(root->left, target - root->val, cur, res);
binaryTreePathHelper(root->right, target - root->val, cur, res);
}
cur->pop_back();
}
};