【leetcode】Python实现-112.路径总和

描述

【leetcode】Python实现-112.路径总和_第1张图片

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

稍微优化

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

你可能感兴趣的:(leetcode)