1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int target) { if (root == nullptr) { return {}; } vector<int> path; vector<vector<int>> ans; int currentSum = 0; FindPath(root, target, path, currentSum, ans); return ans; }
void FindPath(TreeNode* root, int target, vector<int>& path, int currentSum, vector<vector<int>>& ans) { currentSum += root->val; path.push_back(root->val); bool isLeaf = root->left == nullptr && root->right == nullptr; if (currentSum == target && isLeaf) { ans.push_back(path); } if (root->left != nullptr) { FindPath(root->left, target, path, currentSum, ans); } if (root->right != nullptr) { FindPath(root->right, target, path, currentSum, ans); } path.pop_back(); } };
|