使用递归的方法,传递path变量,sum减去经过path经过节点的值,最后为0,且为根节点即可。
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> path;
vector<vector<int>> allPath;
findPath(root, sum, path, allPath);
return allPath;
}
void findPath(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &allPath)
{
if(!root) return;
sum -= root->val;
path.push_back(root->val);
if(!root->left && !root->right)
{ if(sum == 0)
allPath.push_back(path);
}
else
{
if(root->left) findPath(root->left, sum, path, allPath);
if(root->right) findPath(root->right, sum, path, allPath);
}
path.pop_back();
}
};