




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.
1class TreeNode {
2    int val;
3    TreeNode left;
4    TreeNode right;
5    TreeNode(int val) { this.val = val; }
6}
7
8class Solution {
9    public boolean hasPathSum(TreeNode root, int targetSum) {
10        if (root == null) return false;
11        if (root.left == null && root.right == null) return root.val == targetSum;
12        targetSum -= root.val;
13        return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
14    }
15}This Java implementation uses a class Solution with a similar recursive approach. The method hasPathSum checks whether the current node is null (base case) and evaluates leaf nodes for the target sum condition, recursing on both left and right children otherwise.
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).
public class Solution {
    public bool HasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        Stack<int> sums = new Stack<int>();
        stack.Push(root);
        sums.Push(root.val);
        while (stack.Count > 0) {
            TreeNode currentNode = stack.Pop();
            int currSum = sums.Pop();
            if (currentNode.left == null && currentNode.right == null && currSum == targetSum) {
                return true;
            }
            if (currentNode.right != null) {
                stack.Push(currentNode.right);
                sums.Push(currSum + currentNode.right.val);
            }
            if (currentNode.left != null) {
                stack.Push(currentNode.left);
                sums.Push(currSum + currentNode.left.val);
            }
        }
        return false;
    }
}The C# solution applies stacks as a strategy to iterate over potential paths, capturing each sum iteratively per node traversal. Each operand in the stack records requisite path data while managing traversal robustness manually.