51. Path Sum

51. Path Sum

Easy
45.0%
3.0k
dfsbfstreebinary-treestackrecursion
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

A large-scale platform (such as a financial system, recommendation engine, or monitoring service) represents decision flows and hierarchical computations using binary trees.

Each node in the tree represents:

  • a transaction value
  • a scoring metric
  • or a decision weight

The system needs to validate whether a specific cumulative value can be achieved by following a valid path from the root to a terminal node.

This is particularly useful in:

  • validating transaction chains
  • checking scoring thresholds
  • analyzing decision outcomes

The system defines a valid path as a path starting from the root and ending at a leaf node (a node with no children).

The platform receives:

  • a binary tree (root)
  • a target value (targetSum)

It must determine whether any root-to-leaf path exists such that the sum of node values equals the target.

This is a common practice coding problem frequently asked in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given the root of a binary tree and an integer targetSum, return:

  • true if there exists a root-to-leaf path where the sum equals targetSum
  • false otherwise

Input Format

  • root: root of the binary tree
  • targetSum: integer

Each node:

TreeNode { int val; TreeNode left; TreeNode right;}

Output Format

  • Boolean (true or false)

Examples

Example 1:

Input: s = Tree, targetSum = 22 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
Output: true
Explanation: Path: 5 → 4 → 11 → 2 = 22

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: No root-to-leaf path sums to 5

Example 3:

Input: root = [], targetSum = 0
Output: false

Constraints

  • 0 ≤ number of nodes ≤ 100,000
  • -1000 ≤ Node.val ≤ 1000
  • -1000 ≤ targetSum ≤ 1000

Loading editor...

[5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
true

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback