按模板,1,2,3,4步,可以查看代码随想录中的回溯精讲
/**
* 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 {
vector<int> temp;
vector<vector<int>> res;
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root, target);
return res;
}
void dfs(TreeNode*root, int target){
// 题目说了是从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
// 因此没必要去减枝
// 1. 递归终止条件
if(root==nullptr)
return;
// 2.访问当前结点
temp.push_back(root->val);
target -= root->val;
if(target==0 && !root->left && !root->right){
// 根据题目要求,最后一个结点一定是根节点,所以加上后面两个条件
res.push_back(temp);
// 不要return,否则不会撤销这个结点
}
// 3. 递归左右子树
if(root->left)
dfs(root->left, target);
if(root->right)
dfs(root->right, target);
// 4. 撤销当前结点
target += root->val;
temp.pop_back();
}
};