




Sponsored
Sponsored
This approach uses a recursive DFS strategy to navigate from the root to each leaf, calculating the cumulative sum along the path. If we find a path where the cumulative sum equals the targetSum at a leaf node, we return true. Otherwise, we continue exploring other paths. In case we exhaust all paths without finding a valid path, we return false.
Time Complexity: O(N), where N is the number of nodes in the tree, as we have to visit each node.
Space Complexity: O(H), where H is the height of the tree due to the recursion stack.
1function TreeNode(val, left = null, right = null) {
2    this.val = val;
3    this.left = left;
4    this.right = right;
5}
6
7var hasPathSum = function(root, targetSum) {
8    if (!root) return false;
9    if (!root.left && !root.right) return root.val === targetSum;
10    targetSum -= root.val;
11    return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
12};The JavaScript implementation utilizes a functional approach with an anonymous function expression to perform recursive depth-first searches, with conditions similarly prioritized for leaf nodes and each path’s cumulative sum against the target.
In contrast to the recursive method, this approach utilizes an explicit stack to iteratively perform DFS, tracking the cumulative sum along each path. Nodes are pushed onto the stack with their cumulative sums traversed thus far, effectively replacing the recursion stack with an explicit stack to manage state manually. This can help in environments with limited recursion support.
Time Complexity: O(N), examining each node iteratively.
Space Complexity: O(N), as the stack could store up to all nodes in the worst scenario (e.g., a path-heavy tree with a single path).
This Java solution uses two stacks to iteratively explore paths. The first stack stores tree nodes, while the second tracks the cumulative sum. At each step, we check if a leaf node satisfies the required sum, managing iterative state manually.