/** * 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> result; vector path; void dfs(TreeNode* root, vector& path, int sum, int target){ if(root == nullptr) return; path.push_back(root->val); sum += root->val; if(sum == target && root->left == nullptr && root->right == nullptr){ result.push_back(path); } dfs(root->left, path, sum, target); dfs(root->right, path, sum, target); path.pop_back(); } vector> pathSum(TreeNode* root, int targetSum) { dfs(root, path, 0, targetSum); return result; } };