Katkat

Check Root-To-Leaf Target Sums In A Binary Tree

Hudson River TradingSoftware Engineer · Technical Screen

Last updated

This question tests your ability to traverse a binary tree using depth-first search (DFS) or breadth-first search (BFS) while tracking path accumulators and accurately identifying valid leaf nodes.

Problem Statement

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

A leaf is defined as a node with no children (both left and right child pointers are None). An empty tree contains no root-to-leaf paths.

Function Interface

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def has_path_sum(root: TreeNode | None, target_sum: int) -> bool:
    pass

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • `-10^5 <= target_sum 4 -> 11 -> 2 sums to 22 (5 + 4 + 11 + 2 = 22).

### Example 2

```text
Input:
      1
     /
    2
target_sum = 1

Output: False
Explanation: Although the root has value 1, it is not a leaf node because it has a left child. The only root-to-leaf path is 1 -> 2 with sum 3.

Example 3

Input: root = None, target_sum = 0
Output: False
Explanation: Since the tree is empty, no root-to-leaf paths exist.

Edge Cases to Consider

  • Empty tree: Should return False regardless of whether target_sum is 0.
  • Single node: The single node is itself a leaf; return node.val == target_sum.
  • Negative node values and target sums: Paths may decrease or fluctuate in cumulative sum, so you cannot prune search paths early solely based on the current running sum exceeding target_sum.
  • Nodes with only one child: A node with only one child is not a leaf; traversing must continue down the non-null branch.

Hints

Hint 1

Carefully define the base cases: an empty node should return false, but a leaf node should check whether the remaining target equals the leaf's value.

Hint 2

Be cautious not to treat a node with only one child as a leaf; you must only validate the target sum when both left and right pointers are null.

Hint 3

Because node values can be negative, do not prematurely terminate a branch just because the current path sum exceeds the target sum.

Follow-up questions

  • How would you return all root-to-leaf paths that match the target sum instead of just returning a boolean?
  • How would you solve this iteratively using an explicit stack or queue, and what are the trade-offs in memory usage?
  • If the tree could be extremely deep (e.g., skewed tree with 10^5 nodes), how would you avoid stack overflow in languages with fixed recursion limits?