# Path Sum

Published: Oct 4, 2022

Easy Depth-First Search Binary Tree

## Introduction

The pre-order traversal works to find the answer. When the depth-first search (recursion) approach is taken, we should be careful about the value consistency when the process comes back from deeper stack. Other than that, the problem is just a tree traversal.

## Problem Description

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.

Constraints:

• The number of nodes in the tree is in the range `[0, 5000]`.
• `-1000 <= Node.val <= 1000`
• `-1000 <= targetSum <= 1000`

https://leetcode.com/problems/path-sum/

## Examples

``````Example 1
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation:
5
/   \
4      8
/      /   \
11      13    4
/  \            \
7    2            1
Path: 5 -> 4 -> 11 -> 2
``````
``````Example 2
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation:
1
/  \
2    3
``````
``````Example 3
Input: root = [], targetSum = 0
Output: false
Explanation: The tree is empty.
``````

## Analysis

The solution here takes the pre-order traversal approach (depth-first search). The first step is to subtract the root value from the given targetSum. If the current node is a leaf, check the targetSum becomes zero. The left or right subtree returns true if the targetSum exists.

## Solution

``````# 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 PathSum:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
targetSum -= root.val
if not root.left and not root.right:
return targetSum == 0
left = self.hasPathSum(root.left, targetSum)
right = self.hasPathSum(root.right, targetSum)
return left or right
``````

## Complexities

• Time: `O(n)`
• Space: `O(1)`