Path Sum

Problem Id: 112 Difficulty: Easy Tag: Tree Tag: 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)