LeetCode: Path Sum Solution

Keep subtracting

Approach

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 false
3 if (!root.left && !root.right) return root.val === targetSum
4 targetSum -= root.val
5 return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum)
6}

References

Original problem

Similar problems

Path Sum II

Binary Tree Maximum Path Sum

Sum Root to Leaf Numbers

Path Sum III

Path Sum IV

Comments

Loading comments...

Tags

leetcode

tree

binary tree

dfs

recursion

Next Post

LeetCode: Search a 2D Matrix

Sep 12, 2022

Flatten into 1D array

Previous Post

LeetCode: Path Sum III

Sep 9, 2022

If timebox exceeded, read other solutions

HoningJS

Search Posts