/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void findPath(TreeNode* root, int sum_target, vector<int>& V, int sum_now, vector<vector<int>>& result) {
V.push_back(root->val);
sum_now += root->val;
if(!root->left && !root->right && sum_now == sum_target) result.push_back(V);
if(root->left) findPath(root->left, sum_target, V, sum_now, result);
if(root->right) findPath(root->right, sum_target, V, sum_now, result);
V.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> V;
vector<vector<int>> result;
if(root) findPath(root, sum, V, 0, result);
return result;
}
};
【leetcode 二叉树 DFS】【剑指 Offer】 34. 二叉树中和为某一值的路径 C++
最新推荐文章于 2023-05-13 12:00:39 发布