Path Sum II(C++路径总和 II)

亦凉 2022-10-13 05:13 294阅读 0赞

(1)递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. private:
  14. vector<vector<int>> vec;
  15. public:
  16. void helper(vector<int> v,TreeNode *root,int target) {
  17. if(!root) return;
  18. if(target-root->val==0 && !root->left && !root->right) {
  19. v.push_back(root->val);
  20. vec.push_back(v);
  21. }
  22. v.push_back(root->val);
  23. helper(v,root->left,target-root->val);
  24. helper(v,root->right,target-root->val);
  25. return;
  26. }
  27. vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
  28. vector<int> v;
  29. helper(v,root,targetSum);
  30. return vec;
  31. }
  32. };

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 112.Path Sum (路径总和)

    题目描述: 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。 说明: 叶子节点是指没有子节点的节点。 示例: