题目来源:https://leetcode.cn/problems/path-sum-ii/description/
C++题解:采用递归法,前序遍历,遍历每个叶子节点,路径和满足条件则将该路径保存下来。
class Solution {
public:
void getlujing(TreeNode* node, int targetSum, int sumtmp, vector<int> lujing, vector<vector<int>>& result) {
sumtmp = sumtmp + node->val;
lujing.push_back(node->val);
if(node->left == nullptr && node->right == nullptr) {
if(sumtmp == targetSum) result.push_back(lujing);
return;
}
if(node->left) getlujing(node->left, targetSum, sumtmp, lujing, result);
if(node->right) getlujing(node->right, targetSum, sumtmp, lujing, result);
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> result;
vector<int> lujing;
int sumtmp = 0;
if(!root) return result;
getlujing(root, targetSum, sumtmp, lujing, result);
return result;
}
};