思路:
当搜索到叶子节点时,我们看当前的s是否为0即可。
代码:
/**
* 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,vector<vector<int>> &ans,vector<int>path,int sum)
{
if(!root)return ;
path.push_back(root->val);
int x=sum-root->val;//先减去这个节点的值,看是否符合条件
if(!root->left&&!root->right&&!x)
{
ans.push_back(path);
}
dfs(root->left,ans,path,x);
dfs(root->right,ans,path,x);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
vector<int>path;
dfs(root,ans,path,sum);
return ans;
}
};