把temp和result都定义在private里面
最后temp.pop_back();
Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths
where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
/**
* 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 {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if(root==NULL){
return result;
}
temp.push_back(root->val);
if(sum-root->val==0&&root->left==NULL&&root->right==NULL){
result.push_back(temp);
}
if(root->left!=NULL){
pathSum(root->left,sum-root->val);
}
if(root->right!=NULL){
pathSum(root->right,sum-root->val);
}
temp.pop_back();//不在函数中定义temp的原因,如果这样的话进temp一个,递归,
// 又更新为一个空的temp,因此函数外定义,函数内清空
return result;
}
private:
vector<int>temp;
vector<vector<int>>result;
};