
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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
6 this.val = val;
7 this.left = left;
8 this.right = right;
9 }
10}
11
12public class Solution {
13 public bool HasPathSum(TreeNode root, int targetSum) {
14 if (root == null) return false;
15 if (root.left == null && root.right == null) return root.val == targetSum;
16 targetSum -= root.val;
17 return HasPathSum(root.left, targetSum) || HasPathSum(root.right, targetSum);
18 }
19}This C# solution mirrors the approach of evaluating at each TreeNode if the current path sum could potentially satisfy the target sum, focusing particularly on when a leaf node is encountered.
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).
The C implementation introduces a tailored stack structure for managing nodes and their path sums. Operations are performed iteratively through custom stack manipulations, proceeding to separately check trees adjusting path sums dimensionally.