




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.
1struct TreeNode {
2    int val;
3    TreeNode *left;
4    TreeNode *right;
5    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
6};
7
8class Solution {
9public:
10    bool hasPathSum(TreeNode* root, int targetSum) {
11        if (!root) return false;
12        if (!root->left && !root->right) return root->val == targetSum;
13        targetSum -= root->val;
14        return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
15    }
16};The C++ solution follows a similar recursive DFS approach with a class Solution encapsulating the logic. The function checks for null root and evaluates when leaf nodes are reached, recursing further by updating the targetSum.
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.