FrontendX
Path Sum
easy
Description
AI Assistance
Solution
Test Cases
Test Result
Submissions
Canvas
Path
Sum
Given a binary tree and a target sum, return true if there exists a root-to-leaf path with that sum.
Examples
Example 1
Input:
[[5,4,8,11,null,13,4,7,2,null,null,null,1],22]
Output:
true
Example 2
Input:
[[1,2,3],5]
Output:
false
Hints
Hint 1
Use a depth-first search (DFS) approach to traverse the tree, keeping track of the remaining sum as you go.
Hint 2
Implement a recursive helper function that checks if the current node is a leaf and if the remaining sum equals the node's value.
Hint 3
Handle edge cases where the tree is empty or the root is null by returning false immediately.
Related Problems
maximum-depth-of-binary-tree
same-tree
invert-binary-tree
Path Sum
Given a binary tree and a target sum, return true if there exists a root-to-leaf path with that sum.