1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| vector<vector<int>> pathSum(TreeNode* root, int target) { vector<vector<int>> res; vector<int> path; int currentSum = 0; findPath(root, target, currentSum, path, res); return res; }
void findPath(TreeNode* root, const int target, int& currentSum, vector<int>& path, vector<vector<int>>& res) { if (!root) return; currentSum += root->val; path.push_back(root->val);
if (currentSum == target && !root->left && !root->right) { res.push_back(path); }
if (root->left) findPath(root->left, target, currentSum, path, res); if (root->right) findPath(root->right, target, currentSum, path, res);
currentSum -= root->val; path.pop_back(); }
|