113. 路径总和 II
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
终止条件一定要找好。
首先一定要到叶子结点,sum == target 或者是 sum != target
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
int sum = 0;
void backtracking(TreeNode* cur, int targetSum){
if(cur->left == nullptr && cur->right == nullptr ){//终止条件:到叶子结点
if(sum == targetSum){
res.push_back(path);
}
return ;
}
if(cur->left != nullptr){
sum += cur->left->val;
path.push_back(cur->left->val);
backtracking(cur->left, targetSum);
path.pop_back();
sum -= cur->left->val;
}
if(cur->right != nullptr){
sum += cur->right->val;
path.push_back(cur->right->val);
backtracking(cur->right, targetSum);
path.pop_back();
sum -= cur->right->val;
}
return ;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
if(root == nullptr) return res;
res.clear();
path.clear();
sum += root->val;
//别忘了加进去
path.push_back(root->val);
backtracking(root, targetSum);
return res;
}
};