112. Path Sum

Information

  • Diffculty: Easy

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

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

  • Tags: Tree, Depth-first Search

Intuition

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

Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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)