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 whose two child spots are both 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.
challenge icon

Follow-up

Can you count the paths that add up to targetSum if a path may start at any node and end at any node below it?

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

Test #1

Test #2

Test #3

Arguments

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

Expected Output

true