LeetCode: Path Sum Solution
Keep subtractingApproach
Subtract targetSum
by node.val
during traversal
When reaching leaf node, if targetSum
is equal to node.val
then there exist a path
Implementation
1var hasPathSum = function (root, targetSum) {2 if (!root) return false3 if (!root.left && !root.right) return root.val === targetSum4 targetSum -= root.val5 return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum)6}
References
Similar problems
Path Sum II
Binary Tree Maximum Path Sum
Sum Root to Leaf Numbers
Path Sum IV
Comments
Loading comments...
Tags
leetcode
tree
binary tree
dfs
recursion
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Search a 2D Matrix
Flatten into 1D array
Previous Post
LeetCode: Path Sum III
If timebox exceeded, read other solutions