Path Sum — LeetCode 112 Python Solution

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#112
Reading time
3 min

The problem

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. A leaf is a node with no children.

Example

Input
root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output
true
Explanation
The root-to-leaf path with the target sum is shown.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        def dfs(root, s):
            if root is None:
                return False
            s += root.val
            if root.left is None and root.right is None and s == targetSum:
                return True
            return dfs(root.left, s) or dfs(root.right, s)

        return dfs(root, 0)

Complexity

MeasureComplexity
TimeO(n), where n is the number of nodes in the binary tree
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 112. Path Sum is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 112. Path Sum?
LeetCode 112. Path Sum is rated Easy on LeetCode.
What is the time complexity of LeetCode 112. Path Sum?
The Python solution on this page runs in O(n), where n is the number of nodes in the binary tree.
What is the space complexity of LeetCode 112. Path Sum?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 112. Path Sum cover?
LeetCode 112. Path Sum is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview