Path Sum Visualizer & Step-by-Step Algorithm Solution

Determine if the binary tree has a root-to-leaf path such that adding up all values along the path equals targetSum.

Category: trees | Difficulty: Easy

Tags: DFS, Binary Tree, Recursion, Path Sum, Backtracking

Path Sum

5
4
11
7
2
8
13
4
1
100%
state
targetSum22
remaining22
Initialization
1/13
Explanation

Start hasPathSum with targetSum = 22.

Source Code
1function hasPathSum(root, targetSum) {
2 if (!root) return false;
3 if (!root.left && !root.right) {
4 return targetSum === root.val;
5 }
6 const remaining = targetSum - root.val;
7 return hasPathSum(root.left, remaining) || hasPathSum(root.right, remaining);
8}