思路:回溯
cur_path
记录当前路径中的总和,如果在叶子节点上出现了cur_sum == target_sum
,就将cur_path
放到fit_path
当中。否则就进行回溯操作。- 回溯的“回”如何实现?
cur_path.pop_back()
代码:
/**
* 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>> fit_path;
vector<int> cur_path;
void traceBack(TreeNode* root, int pre_sum, int targetSum) {
if (!root) {
return;
}
int cur_sum = pre_sum + root->val;
cur_path.push_back(root->val);
if (!root->left && !root->right) {
if (cur_sum == targetSum) {
fit_path.push_back(cur_path);
}
}
traceBack(root->left, cur_sum, targetSum);
traceBack(root->right, cur_sum, targetSum);
// 回溯的“回”操作
cur_path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
traceBack(root, 0, targetSum);
return fit_path;
}
};