思路:利用回溯的思想,回溯的退出条件为当前节点为空,是符合路径的判断条件为路径和为目标值且叶子节点包含了,代码如下:
/**
* 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;
vector<vector<int>> pathTarget(TreeNode* root, int target) {
backtrack(root,target);
return res;
}
void backtrack(TreeNode* root, int target){
if(root == nullptr) return;
//路径写入当前节点的值
path.push_back(root->val);
//如果当前节点加上之后等于target且当前节点为叶子节点则将当前路径写入结果中
if(target - root->val ==0 &&root->left == nullptr &&root->right == nullptr){
res.push_back(path);
}
//向左右节点回溯
//如果root为叶节点则不回溯了,并且路径中弹出root->val
backtrack(root->left,target-root->val);
backtrack(root->right,target-root->val);
path.pop_back();
}
};