python实现leetcode之112. 路径总和

2021-09-29  本文已影响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
效果图
上一篇 下一篇

猜你喜欢

热点阅读