Path Sum (Binary Tree)

Data Structures
Easy
Google
111.4K views

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`.

Why Interviewers Ask This

Google interviewers ask the Path Sum problem to evaluate a candidate's mastery of recursive thinking and tree traversal fundamentals. This question specifically tests the ability to maintain state across recursion levels without using global variables, ensuring candidates can handle backtracking logic cleanly while managing edge cases like null nodes or negative integers effectively.

How to Answer This Question

1. Clarify requirements immediately by asking if the tree contains only positive integers, as this impacts optimization strategies for early pruning. 2. Propose a Depth-First Search (DFS) approach using recursion, explicitly stating that you will pass the remaining target sum down each branch rather than accumulating a total from the root. 3. Define your base cases clearly: return true if you reach a leaf node where the remaining sum matches the node's value, and false if the node is null. 4. Implement the recursive step by subtracting the current node's value from the target and calling the function on both left and right children, returning true if either path succeeds. 5. Discuss time complexity as O(N) since you may visit every node, and space complexity as O(H) for the call stack, where H is the tree height, explaining how balanced versus skewed trees affect performance.

Key Points to Cover

  • Explicitly handling the distinction between internal nodes and leaf nodes
  • Passing the 'remaining sum' down the recursion instead of accumulating a total
  • Correctly identifying base cases for null nodes and leaf nodes
  • Analyzing space complexity based on tree height rather than just N
  • Demonstrating clean code structure without relying on global variables

Sample Answer

To solve the Path Sum problem efficiently, I would use a recursive Depth-First Search strategy. First, I'd clarify with the interviewer if the tree values are strictly positive, which could allow for early termination if…

Common Mistakes to Avoid

  • Treating any node with matching sum as a success without verifying it is actually a leaf
  • Using global variables to track the current path sum instead of passing arguments
  • Failing to handle the edge case where the input tree root is null
  • Incorrectly implementing the logic to combine results from left and right subtrees

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 166 Data Structures questionsBrowse all 145 Google questions