题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
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) {} * }; */ 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<int> path; vector<vector<int> > paths; if( root == nullptr ){ return paths; } func( root,target,path,paths ); return paths; } void func(TreeNode* root, int target, vector<int> &q, vector<vector<int> > &paths){ target -= root->val; q.push_back(root->val); if( target == 0 ){ if( root->left == nullptr && root->right == nullptr ){ paths.push_back(q); } }else{ if( root->left != nullptr ) func( root->left,target,q,paths ); if( root->right != nullptr ) func( root->right,target,q,paths ); } q.pop_back(); } };