




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    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7def hasPathSum(root, targetSum):
8    if not root:
9        return False
10    if not root.left and not root.right:
11        return root.val == targetSum
12    targetSum -= root.val
13    return hasPathSum(root.left, targetSum) or hasPathSum(root.right, targetSum)In this Python solution, we define a recursive function hasPathSum that deducts the current node's value from targetSum as we traverse the tree. If we reach a leaf node (both children are None) and the remaining targetSum equals the leaf node's value, we return true; otherwise, false. The recursion continues for left and right subtrees.
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).
1
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.