2019-10-07 LC 112. Path Sum

Description

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

Solution

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

你可能感兴趣的:(2019-10-07 LC 112. Path Sum)