题目来源:https://leetcode.cn/problems/path-sum-ii/description/
C++题解:采用递归法,前序遍历,遍历每个叶子节点,路径和满足条件则将该路径保存下来。文章来源:https://www.toymoban.com/news/detail-515675.html
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;
}
};
文章来源地址https://www.toymoban.com/news/detail-515675.html
到了这里,关于力扣 113. 路径总和 II的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!