-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPathSum.cpp
More file actions
49 lines (46 loc) · 1.24 KB
/
Copy pathPathSum.cpp
File metadata and controls
49 lines (46 loc) · 1.24 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
/**
Definition for binary tree
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (NULL == root)
return false;
if (!root->left && !root->right && root->val == sum)
return true;
else
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> tmp;
if (!root)
return result;
pathSumII(root, result, tmp, sum);
return result;
}
void pathSumII(TreeNode *root, vector<vector<int> > &result, vector<int> &tmp, int sum)
{
tmp.push_back(root->val);
if (!root->left && !root->right && sum == root->val)
{
result.push_back(tmp);
return;
}
if (root->left)
{
pathSumII(root->left, result, tmp, sum - root->val);
}
if (root->right)
{
pathSumII(root->right, result, tmp, sum - root->val);
}
tmp.pop_back();
}
};