美文网首页
python实现leetcode之112. 路径总和

python实现leetcode之112. 路径总和

作者: 深圳都这么冷 | 来源:发表于2021-09-29 00:12 被阅读0次

解题思路

深度优先,遍历的时候减去走过节点的值,针对差值df继续
如果达到叶子结点,判断df是不是刚好为0
否则,对左右子节点作递归即可

112. 路径总和

代码

# 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 hasPathSum(self, root, s):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: bool
        """
        if not root: return False
        df = s - root.val
        if is_leaf(root): return df == 0
        return self.hasPathSum(root.left, df) or self.hasPathSum(root.right, df)


def is_leaf(node):
    return not node.left and not node.right
效果图

相关文章

网友评论

      本文标题:python实现leetcode之112. 路径总和

      本文链接:https://www.haomeiwen.com/subject/fsufnltx.html