前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T124-路径总和 II

【leetcode刷题】T124-路径总和 II

作者头像
木又AI帮
发布2019-07-30 11:25:15
3030
发布2019-07-30 11:25:15
举报
文章被收录于专栏:木又AI帮木又AI帮

leetcode第113题:路径总和 II

https://leetcode-cn.com/problems/path-sum-ii/


【题目】

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

代码语言:javascript
复制
示例:
给定如下二叉树,以及目标和 sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
返回:
[
   [5,4,11,2],
   [5,8,4,5]
]

【思路】

本题和【T123-路径总和】类似,只是需要保存满足条件的路径。

解题思路和上一题稍微有点不同,如果当前节点为NULL,则返回;如果当前节点是叶子节点,则判断是否和sum相等,相等则添加路径;其他情况,继续递归遍历左子树和右子树(即使为空也没关系,因为有判断,不会error)。

【代码】

python版本

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        res = []
        self.get_path_sum(root, [], res, sum)
        return res

    def get_path_sum(self, node, cur, res, sum):
        if not node:
            return
        if not node.left and not node.right:
            if node.val == sum:
                cur.append(node.val)
                res.append(cur)
            return 
        cur.append(node.val)
        self.get_path_sum(node.left, copy.copy(cur), res, sum-node.val)
        self.get_path_sum(node.right, copy.copy(cur), res, sum-node.val)

C++版本

代码语言:javascript
复制
/**
 * 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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> cur;
        get_path_sum(root, cur, res, sum);
        return res;
    }

    void get_path_sum(TreeNode* node, vector<int> cur, vector<vector<int>>& res, int sum){
        if(!node)
            return;
        if(!node->left && !node->right){
            if(node->val == sum){
                cur.push_back(node->val);
                res.push_back(cur);
            }
            return;
        }
        cur.push_back(node->val);
        get_path_sum(node->left, cur, res, sum-node->val);
        get_path_sum(node->right, cur, res, sum-node->val);
    }
};

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档