
Problem
Solution
Submissions
Path Sum
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Given the root of a binary tree and an integer targetSum, determine 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 1
- Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
- Output: true
- Explanation:
Step 1: Start from the root (5)
Step 2: Follow the path: 5 -> 4 -> 11 -> 2
Step 3: Sum the values: 5 + 4 + 11 + 2 = 22 Step 4: Since the sum equals the target and the path ends at a leaf node, return true
Example 2
- Input: root = [1,2,3], targetSum = 5
- Output: false
- Explanation:
Step 1: Start from the root (1)
Step 2: Follow path 1: 1 -> 2 = 3 (not equal to targetSum)
Step 3: Follow path 2: 1 -> 3 = 4 (not equal to targetSum)
Step 4: No root-to-leaf path sums to 5, so return false
Constraints
- The number of nodes in the tree is in the range [0, 5000]
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
- Time Complexity: O(n) where n is the number of nodes
- Space Complexity: O(h) where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a recursive depth-first search approach
- At each node, subtract its value from the target sum
- If you reach a leaf node and the remaining sum equals the node's value, return true
- If you reach a leaf node and the remaining sum doesn't equal the node's value, return false
- For non-leaf nodes, recursively check both left and right subtrees