主页有其他数据结构内容(持续更新中)
难度:Medium
代码:
/**
* 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:
void dfs(TreeNode* root, int sum, vector<int> path, vector<vector<int>>& res) {
if (root == nullptr) {
return;
}
sum -= root->val;
path.emplace_back(root->val);
if (root->left == nullptr && root->right == nullptr && sum == 0) {
// 碰到了叶子节点
res.emplace_back(path);
return;
}
dfs(root->left, sum, path, res);
dfs(root->right, sum, path, res);
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> path;
vector<vector<int>> res;
dfs(root, targetSum, path, res);
return res;
}
};