-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path Sum II.cpp
33 lines (33 loc) · 929 Bytes
/
Path Sum II.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<int> vec;//千万不要定义成局部变量
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > back;
pathSum(root,back,sum,0);
return back;
}
void pathSum(TreeNode* root,vector<vector<int> >& back,int sum,int curSum)
{
if(root==NULL)return;
curSum+=root->val;
vec.push_back(root->val);
bool isLeaf=(root->left==NULL&&root->right==NULL);
if(curSum==sum&&isLeaf)
{
back.push_back(vec);
}
if(root->left!=NULL)pathSum(root->left,back,sum,curSum);
if(root->right!=NULL)pathSum(root->right,back,sum,curSum);
vec.pop_back();
}
};