先序遍历+记录路径
这里少用一个变量用于记录节点和:target-root->val==0&&root->left==null&&root->right==null时,记录路径。
与遍历不同的是:需要恢复路径,即在访问完当前节点后,path需要pop最后的节点。
/**
* 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>temp;
void dfs(TreeNode*root,int target){
if(root==nullptr) return;
target-=root->val;
temp.push_back(root->val);
if(target==0&&root->left==nullptr&&root->right==nullptr) res.push_back(vector<int>(temp));
dfs(root->left,target);
dfs(root->right,target);
target+=root->val;
temp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root,target);
return res;
}
};