-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreePathSum.cpp
More file actions
53 lines (44 loc) · 1.1 KB
/
Copy pathbinaryTreePathSum.cpp
File metadata and controls
53 lines (44 loc) · 1.1 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
#include <vector>
class TreeNode
{
public:
int val;
TreeNode *left, *right;
TreeNode(int val)
{
this->val = val;
this->left = this->right = NULL;
}
};
class Solution
{
public:
std::vector<std::vector<int>> binaryTreePathSum(TreeNode *root, int target)
{
std::vector<std::vector<int>> result;
if(root == NULL) return result;
std::vector<int> path;
helper(root, 0, target, path, result);
return result;
}
void helper(TreeNode *root, int sum, int target, std::vector<int> path, std::vector<std::vector<int>> &result)
{
if(root->left == NULL && root->right == NULL)
{
if(root->val + sum == target)
{
path.push_back(root->val);
result.push_back(path);
}
}
path.push_back(root->val);
if(root->left)
{
helper(root->left, sum + root->val, target, path, result);
}
if(root->right)
{
helper(root->right, sum + root->val, target, path, result);
}
}
};