📘
Path Sum
Given a binary tree (as a level-order array) and a target sum, return True if the tree has a root-to-leaf path where the values sum to the target.
Example:
Input:
5,4,8,11,null,13,4,7,2,null,null,null,1 22
Output:
True
Reasoning:
- The binary tree is constructed from the level-order array: 5 is the root, 4 and 8 are its children, and so on.
- We traverse all root-to-leaf paths, calculating their sums: 5+4+11+2=22, 5+4+11+1=21, 5+8+13+4=30, 5+8+13+7=33, 5+8+4=17, and 5+8+4+1=18.
- Among these paths, one sum matches the target: 5+4+11+2=22.
- Since a matching path is found, the function returns
True.
Constraints:
- 0 <= number of nodes <= 5000
- -1000 <= Node.val <= 1000
- -1000 <= targetSum <= 1000
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.