/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<vector<int>> res;
vector<int> path;
findPath(root, target, res, path);
return res;
}
void findPath(TreeNode* root, int target, vector<vector<int>>& res, vector<int>& path){
if (root == nullptr) return;
target -= root->val;
path.push_back(root->val);
if (!target && !root->left && !root->right) res.push_back(path);
if (root->left) findPath(root->left, target, res, path);
if (root->right) findPath(root->right, target, res, path);
path.pop_back();
}
};
Leetcode 剑指Offer 34.二叉树中和为某一值的路径
最新推荐文章于 2022-05-10 22:27:38 发布