本文最后更新于621 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
题目链接/文章讲解/视频讲解:https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html
1.这个题也是差不多的思路,看了遍直接就手写了一遍,没什么问题。
CPP
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>>res;
vector<int>path;
void traveral(TreeNode *node , int count){
if(node->left == NULL && node->right == NULL && count == 0){
res.push_back(path);
}
if(node->left == NULL && node->right == NULL && count != 0){
return ;
}
if(node->left){
path.push_back(node->left->val);
count -= node->left->val;
traveral(node->left,count);
count += node->left->val;
path.pop_back();
}
if(node->right){
path.push_back(node->right->val);
count -= node->right->val;
traveral(node->right,count);
count += node->right->val;
path.pop_back();
}
return ;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
path.clear();
res.clear();
if(root == NULL)return res;
if(root != NULL){
path.push_back(root->val);
targetSum -= root->val;
traveral(root,targetSum);
}
return res;
}
};