Coders Crushby Napplied AI
Back to DSA Problems
EasyTrees

Path Sum

Check if root-leaf path equals target

Solution Approach

Use DFS to explore all root-to-leaf paths. Subtract node value from target and check if any path sums to zero.

Implementation
def hasPathSum(root, targetSum):
    if not root:
        return False
    
    if not root.left and not root.right:
        return targetSum == root.val
    
    return (hasPathSum(root.left, targetSum - root.val) or 
            hasPathSum(root.right, targetSum - root.val))
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(h)
Complexity
Time:O(n)
Space:O(h)
Asked at
GoogleMicrosoft
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless