-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_path_sum.cpp
More file actions
54 lines (46 loc) · 1.28 KB
/
Copy pathbinary_tree_path_sum.cpp
File metadata and controls
54 lines (46 loc) · 1.28 KB
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
/**
* 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) {
// Write your code here
vector<vector<int>> result;
vector<int> current;
if (root == NULL) {
return result;
}
helper(result, root, current, 0, target);
return result;
}
void helper(vector<vector<int>> &result, TreeNode *node, vector<int> ¤t, int sum, int target) {
current.push_back(node->val);
sum += node->val;
if (node->left == NULL && node->right == NULL) {
if (sum == target) {
result.push_back(current);
}
}
if (node->left) {
helper(result, node->left, current, sum, target);
}
if (node->right) {
helper(result, node->right, current, sum, target);
}
current.pop_back();
}
};