思路:
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 {
private:
void calPath(vector<vector<int>> &res, vector<int> &ans, int gap, TreeNode *root) {
if(root == nullptr) {
return;
}
ans.push_back(root->val);
if(root->left == nullptr && root->right == nullptr) {
if(gap == root->val) {
res.push_back(ans);
}
}
calPath(res, ans, gap - root->val, root->left);
calPath(res, ans, gap - root->val, root->right);
ans.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> ans;
calPath(res, ans, sum, root);
return res;
}
};