Skip to content
LC-0112 Easy LeetCode

112. Path Sum

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 53% Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(h), h is height of binary tree

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    # @param root, a tree node
    # @param sum, an integer
    # @return a boolean
    def hasPathSum(self, root, sum):
        if root is None:
            return False

        if root.left is None and root.right is None and root.val == sum:
            return True

        return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)

Solution from kamyu104/LeetCode-Solutions · MIT