112. Path Sum ๐
Last updated
Last updated
Difficulty: Easy
- Tags: Binary Tree
, Depth-First Search (DFS)
, Recursion
Given the root of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that the sum of all the node values along the path equals targetSum
.
A leaf is a node with no children.
๐น Example 1:
Input:
Output:
Explanation:
The root-to-leaf path [5,4,11,2]
has a sum of 22
.
๐น Example 2:
Input:
Output:
Explanation:
There are two root-to-leaf paths:
Path 1 -> 2
: Sum is 3
.
Path 1 -> 3
: Sum is 4
.
Neither equals 5
.
๐น Example 3:
Input:
Output:
Explanation:
The tree is empty, so there are no root-to-leaf paths.
The number of nodes in the tree is in the range [0, 5000]
.
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
To determine if there is a root-to-leaf path with the given targetSum
:
Use Depth-First Search (DFS) to traverse the binary tree.
Subtract the current node's value from targetSum
as you traverse.
Check if:
The current node is a leaf.
The updated targetSum
equals 0
.
Base Case:
If the root is null
, the tree is empty, and no path exists.
Leaf Node Check:
If the node has no children, compare its value to the remaining targetSum
.
Recursive Calls:
Subtract the current node's value from targetSum
.
Recursively check the left and right subtrees.
Combine Results:
Use the logical OR
operator to combine results from both subtrees.
O(n): Each node is visited once.
O(h): Where h
is the height of the tree (due to recursion stack).
How would you modify this solution to return all paths with the target sum?
Can you solve this iteratively instead of using recursion?
You can find the full solution here.