给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]
解题思路
dfs
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
dfs(root, target);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void dfs(TreeNode* root, int target) {
if(root == nullptr) return;
path.emplace_back(root->val);
target -= root->val;
if(root->left == nullptr && root->right == nullptr && target == 0) {
res.emplace_back(path);
}
dfs(root->left, target);
dfs(root->right, target);
path.pop_back();
}
};