PIXELBANKv9.1.0
Menu

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=225 + 4 + 11 + 2 = 22, 5+4+11+1=215 + 4 + 11 + 1 = 21, 5+8+13+4=305 + 8 + 13 + 4 = 30, 5+8+13+7=335 + 8 + 13 + 7 = 33, 5+8+4=175 + 8 + 4 = 17, and 5+8+4+1=185 + 8 + 4 + 1 = 18.
  • Among these paths, one sum matches the target: 5+4+11+2=225 + 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 locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.