Path Sum

Easy
DFS

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example Tree:

        5
       / \
      4   8
     /   / \
    11  13  4
   /  \      \
  7    2      1

Target Sum: 22 Result: true (path 5 -> 4 -> 11 -> 2 = 22)

Key Insight: Use DFS to explore all root-to-leaf paths. At each step, subtract the current node's value from the target. If we reach a leaf node where the remaining target equals the node's value, we found a valid path.

Example 1

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The path 5 -> 4 -> 11 -> 2 sums to 22.

Example 2

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: Paths are 1->2 (sum=3) and 1->3 (sum=4). Neither equals 5.

Example 3

Input: root = [], targetSum = 0
Output: false
Explanation: Empty tree has no paths, so no path sum can equal any target.

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
Show Hints (4)
Hint 1: What defines a valid ending point? It must be a leaf node (no children).
Hint 2: Instead of tracking the sum, try subtracting each node value from the target. When do you know you found a valid path?
Hint 3: At a leaf node, check if the remaining target equals the leaf value.
Hint 4: Remember: paths must go from root to leaf, not stop at internal nodes!
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?