
Problem
Solution
Submissions
Path Sum in Binary Tree
Certification: Basic Level
Accuracy: 0%
Submissions: 1
Points: 8
Write a Java program to determine if the binary tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Example 1
- Input:
- root = [5,4,8,11,null,13,4,7,2,null,null,null,1]
- targetSum = 22
- Output: true
- Explanation:
- There exists a root-to-leaf path 5 -> 4 -> 11 -> 2 with a sum of 22.
Example 2
- Input:
- root = [1,2,3]
- targetSum = 5
- Output: false
- Explanation:
- There does not exist a path that sums to 5.
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 in the tree.
- 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 approach to traverse all root-to-leaf paths.
- At each node, subtract the node's value from the target sum.
- When reaching a leaf node, check if the remaining sum equals the leaf's value.
- A leaf node is one with no children.
- The path must end at a leaf node to be considered valid.