binary-tree
depth-first-search
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 adding up all the values along the path equals targetSum, or false otherwise.
A leaf is a node with no children. A path must start at the root and end at a leaf — it cannot stop partway down.
Input / output
- Input:
root: TreeNode,targetSum: int(JSON test fixture forrootis a LeetCode-style level-order array, e.g.[5,4,8,11,null,13,4,7,2,null,null,null,1], withnullfor a missing child) - Output:
boolean
Constraints
- 0 <= number of nodes <= 5,000
- -1,000 <= node value <= 1,000
- -1,000 <= targetSum <= 1,000
Follow-up
Can you solve it iteratively with an explicit stack instead of recursion, tracking the running sum alongside each node?
Examples
Example 1
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Example 2
Input: root = [1,2,3], targetSum = 5
Output: false
Example 3 (empty tree)
Input: root = [], targetSum = 0
Output: false
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.