注意dfs时参数的传递。
/**
* 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:
int target;
vector<int> path;
vector<vector<int>>ans;
void dfs(TreeNode* root, int cur){
if(root == nullptr){
return;
}
cur += root->val;
path.push_back(root->val);
//printf("cur = %d root = %d\n", cur, root->val);
if(root->left == nullptr && root->right == nullptr){
if(cur == target) ans.push_back(path);
}else{
if(root->left) dfs(root->left, cur);
if(root->right) dfs(root->right, cur);
}
path.pop_back();
}
vector<vector<int>> findPath(TreeNode* root, int sum) {
target = sum;
dfs(root, 0);
return ans;
}
};