题目链接:https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=196&rp=1&ru=%2Fexam%2Foj&qru=%2Fexam%2Foj&sourceUrl=%2Fexam%2Foj%3Fpage%3D2%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=&judgeStatus=&tags=&title=8&gioEnter=menu
题目如下:
class Solution {
public:
vector> FindPath(TreeNode* root,int expectNumber) {
if(!root) return res;
sum+=root->val;
path.push_back(root->val);
backtracking(root,expectNumber,sum);
return res;
}
void backtracking(TreeNode* root,int target,int sum){
//if(sum>=target) { //这里错误:终止条件为欸到达叶子节点,而不是这个
if(root->left==nullptr&&root->right==nullptr){
if(sum==target) res.push_back(path);
return;
}
if(root->left){
sum+=root->left->val;
path.push_back(root->left->val);
backtracking(root->left, target, sum);
path.pop_back();
sum-=root->left->val;
}
if(root->right){
sum+=root->right->val;
path.push_back(root->right->val);
backtracking(root->right, target, sum);
path.pop_back();
sum-=root->right->val;
}
}
private:
vector> res;
vector path;
int sum=0;
};



