题解 | 二叉树中和为某一值的路径(二)
二叉树中和为某一值的路径(二)
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 {
private:
vector<vector<int>> res;
vector<int> path;
void findPath(TreeNode* cur, int left){
if(cur == nullptr) return ;
path.push_back(cur->val);
int tmp = cur->val;
left = left - tmp;
if(left == 0 && cur->left == nullptr && cur->right == nullptr) res.push_back(path);
findPath(cur->left,left);
findPath(cur->right,left);
path.pop_back();
}
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > FindPath(TreeNode* root, int target) {
res.clear();
path.clear();
findPath(root, target);
return res;
}
};
查看4道真题和解析