首页 > 其他 > 详细

二叉树中和为某一值的路径

时间:2021-03-27 23:50:51      阅读:25      评论:0      收藏:0      [点我收藏+]

输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径;

/**
 * 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:
    void pathSum(TreeNode* root, int target, std::vector<int>& tmp) {
      if (root == NULL) {
          return;
      }
      int val = root->val;
      int t1 = target - val;
      tmp.push_back(val);
      if (t1 == 0) {
          if (!root->left && !root->right) {
              res.push_back(tmp);
          }
      }
      pathSum(root->left, t1, tmp);
      pathSum(root->right, t1, tmp);
      tmp.erase(tmp.end() - 1);  // 删除最末尾元素,这样形参可以传递引用,减少内存开销
    }
    vector<vector<int>> pathSum(TreeNode* root, int target) {
        std::vector<int> tmp;
        pathSum(root, target, tmp);
        return res;
    }
    std::vector<std::vector<int>> res;
};

 

二叉树中和为某一值的路径

原文:https://www.cnblogs.com/morningsunlll/p/14587133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!