题解 | #牛牛的路径总和#
牛牛的路径总和
https://www.nowcoder.com/practice/45a878da071d43458b8b4cb2db8275b6
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <algorithm> #include <cstddef> #include <ios> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param targetSum int整型 * @return int整型vector<vector<>> */ void backtravel(vector<vector<int>>& res, vector<int>& path, TreeNode* root, int& targetSum) { path.push_back(root->val); targetSum -= root->val; if(root->left == nullptr && root->right == nullptr) { if(targetSum == 0) res.push_back(path); } if(root->left) { backtravel(res, path, root->left, targetSum); path.pop_back(); targetSum += root->left->val; } if(root->right) { backtravel(res, path, root->right, targetSum); path.pop_back(); targetSum += root->right->val; } return; } vector<vector<int>> findPaths(TreeNode* root, int targetSum) { // write code here vector<vector<int>> res; vector<int> path; backtravel(res, path, root, targetSum); return res; } };