题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param target int整型 * @return int整型vector<vector<>> */ vector<vector<int> > FindPath(TreeNode* root, int target) { // write code here vector<vector<int>> result; vector<int> path; dfs(result, path, root, target); return result; } void dfs(vector<vector<int>>& result, vector<int>& path, TreeNode *root, int target) { if (root == nullptr) { return; } cout << "root->val = " << root->val << " target = " << target; path.push_back(root->val); target -= root->val; if (root->left == nullptr && root->right == nullptr && target == 0) { result.push_back(path); cout << "res" << endl; } dfs(result, path, root->left, target); dfs(result, path, root->right, target); path.pop_back(); } };