LeetCode Path Sum II

LeetCode解题之Path Sum II


原题

找出一棵二叉树所有的从根节点到某一叶子节点的路径,该路径上所有节点的和为一个特定值。

注意点:

例子:

输入:

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

输出:

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

解题思路

Path Sum 是判断是否有这样一条路径,现在要把所有的路径都求出来,那只要在dfs时将符合要求的路径加入到结果集。注意加入结果集的数据不要是引用,否则可能之后会再次被修改。

AC源码

# 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]]
        """
        result = []
        self._pathSum(root, sum, [], result)
        return result

    def _pathSum(self, root, sum, curr, result):
        if not root:
            return
        sum -= root.val
        if sum == 0 and root.left is None and root.right is None:
            result.append(curr + [root.val])
        if root.left:
            self._pathSum(root.left, sum, curr + [root.val], result)
        if root.right:
            self._pathSum(root.right, sum, curr + [root.val], result)


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值