具体代码如下:
/**
* 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:
void dfs(TreeNode *root, int &sum, vector<vector<int>> &ans, vector<int> &temp){
if(!root){
return;
}
sum -= root -> val;
temp.push_back(root -> val);
if(!root -> left && !root -> right && !sum) ans.push_back(temp);
dfs(root -> left, sum, ans, temp);
dfs(root -> right, sum, ans, temp);
sum += root -> val;
temp.pop_back();
return;
}
vector<vector<int>> findPath(TreeNode* root, int sum) {
vector<vector<int>> ans;
vector<int> temp;
dfs(root, sum, ans, temp);
return ans;
}
};