【LeetCode】113. Path Sum II 解题报告(Python)

本文介绍了LeetCode上113题Path Sum II的解题思路及Python实现方法。该题旨在寻找一棵二叉树中所有从根节点到叶子节点路径的集合,使得路径上节点值之和等于给定的目标值。文章提供了两种回溯法的解决方案,并详细解释了每一步的处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【LeetCode】113. Path Sum II 解题报告(Python)

标签(空格分隔): LeetCode

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.me/


题目地址:https://leetcode.com/problems/path-sum-ii/description/

题目描述:

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

题目大意

在一棵二叉树中,找出从根节点到叶子节点的和为target的所有路径。

解题方法

其实一看这个题就能看出来这个是经典的回溯法的题目。看来是我手生了,竟然一下没写出来。

我卡在的地方在于回溯的时候root的处理方式,最后有下面两种处理方式吧。我更倾向于第二种,先把root给添加上去再回溯。

# 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.dfs(root, sum, res, [])
        return res

    def dfs(self, root, target, res, path):
        if not root: return
        path += [root.val]
        if sum(path) == target and not root.left and not root.right:
            res.append(path[:])
            return
        if root.left:
            self.dfs(root.left, target, res, path[:])
        if root.right:
            self.dfs(root.right, target, res, path[:])
        path.pop(-1)

换了一种做法,貌似看起来更简单直白了。

# 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]]
        """
        if not root: return []
        res = []
        self.dfs(root, sum, res, [root.val])
        return res

    def dfs(self, root, target, res, path):
        if not root: return
        if sum(path) == target and not root.left and not root.right:
            res.append(path)
            return
        if root.left:
            self.dfs(root.left, target, res, path + [root.left.val])
        if root.right:
            self.dfs(root.right, target, res, path + [root.right.val])

日期

2018 年 6 月 22 日 ———— 这周的糟心事终于完了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值