An interactive visualization of DFS on a binary tree to find a root-to-leaf path with a target sum. Watch the running sum update as the algorithm explores each path.
DFS LeetCode 112 โ Easyroot of a binary tree and an integer targetSum, return true
if the tree has a root-to-leaf path such that adding up all the values along the path
equals targetSum.fun hasPathSum(root: TreeNode?, targetSum: Int): Boolean { if (root == null) { return false } val remaining = targetSum - root.`val` if (root.left == null && root.right == null) { return remaining == 0 } return hasPathSum(root.left, remaining) || hasPathSum(root.right, remaining) }
Instead of tracking a running sum, subtract each node's value from targetSum
as you traverse down the tree. When you reach a leaf node, simply check whether the remaining
targetSum equals zero. This avoids passing an accumulator through the recursion.
null, return False โ there is no path here.targetSum by the current node's value.targetSum == 0.True, a valid path exists.
We visit every node at most once, giving O(n) time where n is the number of nodes.
The recursion stack uses O(h) space where h is the height of the tree โ O(log n) for a
balanced tree and O(n) in the worst case (a skewed tree).