思路:
搜索顺序为自根向下,如果当前节点是叶子节点且target == 0,说明找到一个答案。
代码:
/**
* 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>> pathSum(TreeNode* root, int target) {
dfs(root,target);
return res;
}
void dfs(TreeNode *root,int target){
if(!root) return;
//都是在处理当前点
target -= root->val;
path.push_back(root->val);
if(!root->left && !root->right && !target){
res.push_back(path);
}
dfs(root->left,target);
dfs(root->right,target);
path.pop_back();
}
};
评论区