LeetCode | Path Sum系列问题史上最全讲解(python版)

路径总和系列

[LeetCode112.Path Sum]

给定一个二叉树和一个sum值,判断树中是否存在一条从根节点到叶子节点的路径,使得路径上的值加起来刚好等于sum。

Example:给定如下二叉树,以及目标和 sum = 225
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1
返回: true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

深度优先算法(DFS)

用深度优先算法DFS的思想来遍历每一条完整的路径,也就是利用递归不停找子节点的左右子节点,而调用递归函数的参数只有当前节点和sum值。
首先,如果输入的是一个空节点,则直接返回false,如果如果输入的只有一个根节点,则比较当前根节点的值和参数sum值是否相同,若相同,返回true,否则false。这个条件也是递归的终止条件。
下面我们就要开始递归了,由于函数的返回值是Ture/False,我们可以同时两个方向一起递归,中间用或||连接,只要有一个是True,整个结果就是True。
递归左右节点时,这时候的sum值应该是原sum值减去当前节点的值。

class Solution:
    def hasPathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if root is None:
            return False
        if (root.val == sum) and (root.left is None) and (root.right is None):
            return True
        else:
            return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)     

[Leetcode113.Path Sum II]

在之前判断是否存在和的基础上,需要找出路径。

Example:给定如下二叉树,以及目标和 sum = 225
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1
Output:
[  [5,4,11,2],
   [5,8,4,5] ]

解题思路

定义一个二维的数组result保存结果,每当DFS搜索到新节点时,都要保存该节点至一维数组tmp。每当找出一条路径之后,都将此路径tmp保存到result中。当DFS搜索到子节点,发现不是路径和时,返回上一个结点时,需要把该节点从tmp中移除。

class Solution:
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        self.result = []
        self.tmp = []
        self.find_path(root, sum)
        return self.result

    def find_path(self, node, sum):
        if node is None:
            return
        self.tmp.append(node.val)
        if (node.val == sum) and (node.left is None) and (node.right is None):
            self.result.append(self.tmp)
        else:
            self.find_path(node.left, sum - node.val)
            self.find_path(node.right, sum - node.val)
        self.tmp.pop()

这种方法看似没有什么问题,但是输出的结果是[[],[]],原因可能是当将tmp设为内部属性时,递归同时调用两次find_path会使self.tmp传值失败,append()和pop()不知道谁先执行。这种方法说明,如果设计不好,同时对一个变量有多种操作,很容易出现不可抗力的现象。

改进方法

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

    def find_path(self, node, sum, tmp):
        if node is None:
            return
        if (node.val == sum) and (node.left is None) and (node.right is None):
            self.result.append(tmp + [node.val])
        else:
            self.find_path(node.left, sum - node.val, tmp + [node.val])
            self.find_path(node.right, sum - node.val, tmp + [node.val])            

在改进方法中,我们使用确定的tmp传递每次加入到result中的值,使得出现bug的可能大大降低。

[Leetcode437.Path Sum III]

给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

Example:给定如下二叉树,以及目标和 sum = 810
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1
Output: 3.

和等于 8 的路径有:
1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

一种比较简单的思路,将每个节点都当作根节点来考虑,深度遍历所有节点,记录下此节点向下和为sum的路径个数,然后把所有路径数相加即可。

class Solution:
    def pathSum(self, root, target):
        """
        :type root: TreeNode
        :type target: int
        :rtype: int
        """
        if root == None:
            return 0
        self.num_sum = 0
        self.dfs(root, target)
        return self.num_sum
    
    def dfs(self, root, target):
        if root:
            self.num_sum += self.find_path(root, target)
        if root.left:
            self.dfs(root.left, target)
        if root.right:
            self.dfs(root.right, target)
            
    def find_path(self, node, target):
        """
        :type node:TreeNode
        : rtype:list[int]
        """
        if node == None:
            return 0
        if node.val == target:
            return 1 + self.find_path(node.left, target - node.val) + self.find_path(node.right, target-node.val)
        else:
            return self.find_path(node.left, target - node.val) + self.find_path(node.right, target-node.val)

reference

更多精彩文章,欢迎关注公众号“Li的白日呓语”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值