Menu
CoddyTech

Path Sum

You get a binary tree stored in the array tree in level order, and a number targetSum. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries. Return true if some path from the root down to a leaf has values that add up to targetSum, and false otherwise. A leaf is a node with no children: both of its child spots are empty.

Function

hasPathSum(tree: integer-array, targetSum: integer) → boolean
treeinteger-array
the binary tree in level order, with -1 for an empty spot
targetSuminteger
the total a root-to-leaf path must reach
Returnsboolean
true if some root-to-leaf path adds up to targetSum, false otherwise

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 1000.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • 0 ≤ targetSum ≤ 15000

Examples

Input
tree = [3, 9, 6, -1, 2, 1, 7]targetSum = 14
Output
true
Explanation
The path 3, 9, 2 (indexes 0, 1, 4) adds up to 14, and the 2 at index 4 is a leaf.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Can you count the paths that add up to targetSum when a path may start at any node and end at any node below it, not only run from the root to a leaf?

Reset code
def hasPathSum(tree, targetSum):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [3, 9, 6, -1, 2, 1, 7]
targetSum = 14

Expected

true