Skip to the code
cf.
+10 XP

#354 Route With a Target Total

easy

A quiz app builds a branching story as a binary tree, where each node is a scene worth some points. A player always starts at the top and ends at a scene with no further choices (a leaf).

Write hasRouteTotal(root, target) that returns true if some root-to-leaf path has values adding up to exactly target, and false otherwise. An empty tree has no paths, so it returns false.

Example 1

Input: root = [5,4,8,11,null,13,4], target = 20
Output: true

5 + 4 + 11 = 20.

Example 2

Input: root = [1,2,3], target = 1
Output: false

The root is not a leaf, so the route 1 alone doesn't count.

Constraints

  • 0 <= number of scenes <= 5000
  • -1000 <= points <= 1000
  • -10^6 <= target <= 10^6

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).