1. 程式人生 > >【leetcode】Python實現-112.路徑總和

【leetcode】Python實現-112.路徑總和

描述

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)