51. Path Sum
51. Path Sum
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:
trueif there exists a root-to-leaf path where the sum equalstargetSumfalseotherwise
Input Format
root: root of the binary treetargetSum: integer
Each node:
TreeNode { int val; TreeNode left; TreeNode right;}
Output Format
- Boolean (
trueorfalse)
Examples
Example 1:
s = Tree, targetSum = 22
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1trueExample 2:
root = [1,2,3], targetSum = 5falseExample 3:
root = [], targetSum = 0falseConstraints
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