2019-10-07 LC 112. Path Sum

2019-10-08  本文已影响0人  Mree111

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
上一篇 下一篇

猜你喜欢

热点阅读