#112

Path Sum

Easy
TreeDepth-First SearchBreadth-First SearchBinary TreeDepth-First SearchRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution uses Depth-First Search (DFS) to traverse the tree while keeping track of the remaining targetSum. This approach efficiently checks each path without revisiting nodes.

⚙️

Algorithm

4 steps
  1. 1Step 1: Start DFS from the root node with the initial targetSum.
  2. 2Step 2: Subtract the current node's value from targetSum.
  3. 3Step 3: If a leaf node is reached, check if targetSum is zero.
  4. 4Step 4: Recursively call DFS for left and right children.
solution.py6 lines
1def hasPathSum(root, targetSum):
2    if not root:
3        return False
4    if not root.left and not root.right:
5        return targetSum == root.val
6    return hasPathSum(root.left, targetSum - root.val) or hasPathSum(root.right, targetSum - root.val)

Complexity note: The time complexity is linear because we visit each node once. The space complexity is O(h) due to the recursive call stack, where h is the height of the tree.

  • 1The problem requires understanding of tree traversal techniques like DFS.
  • 2Identifying leaf nodes is crucial for determining valid paths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.