采用先序遍历,遍历二叉树,设置一个vector来存储当前路径,除了遍历到新节点时要记得将节点加入vector外,还有记得树回溯时要把路径也跟着回溯。
/**
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 {
private:
//维护当前路径
vector path;
//结果
vector<vector> res;
public:
vector<vector> pathSum(TreeNode root, int target) {
dfs(root,target);
return res;
}
void dfs(TreeNode* curr,int target){
//忽略空指针
if(curr!=nullptr){
target-=curr->val;
path.push_back(curr->val);
if(target!=0||curr->left!=nullptr||curr->right!=nullptr){
dfs(curr->left,target);
dfs(curr->right,target);
}
else{
//满足结果且为根节点
res.push_back(path);
}
path.pop_back();
}
}
};