112. Path Sum


Do a DFS and check if the required sum equals to the node.val for each leaf if the tree.


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


  • Created: 2020-01-11 16:15:53

  • Last Motified: 2020-01-11 16:15:53

  • Tags: Tree, Depth-first Search