KatInterview

Root-to-Leaf Sum Verification

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsbinary-treedfsiterative

Last updated

Tests depth-first traversal of a binary tree encoded as an indexed array to find paths matching a target sum.

You are given a binary tree represented as a list of nodes and an integer goal. Each node in the list is a tuple (value, left_child_index, right_child_index) where indices reference positions in the same list. An index of -1 indicates the absence of a child. Node 0 is always the root when the tree is non-empty.

Your task is to determine whether any complete path from the root to a leaf has node values that sum to exactly goal.

A leaf is defined as a node where both left_child_index and right_child_index are -1. A node with only one child is not considered a leaf.

If the tree is empty (the input list is empty or None), return False regardless of the goal value.

Constraints

  • The number of nodes in the tree is in the range [0, 10000]
  • -1000 <= node_value <= 1000
  • -100000 <= goal <= 100000
  • Node indices are valid: child indices either equal -1 or reference valid positions in the list
  • The structure forms a valid tree with no cycles

Examples

Example 1

Input: root_to_leaf_sum_exists([[5, 1, 2], [4, 3, -1], [8, 4, 5], [11, 6, 7], [13, -1, -1], [4, -1, 8], [7, -1, -1], [2, -1, -1], [1, -1, -1]], 22)

Output: True

Example 2

Input: root_to_leaf_sum_exists([[1, 1, 2], [2, -1, -1], [3, -1, -1]], 5)

Output: False

Example 3

Input: root_to_leaf_sum_exists([], 0)

Output: False

Hints

Hint 1

Use depth-first traversal while tracking the cumulative sum from the root to the current node.

Hint 2

A node is only a valid endpoint if both of its child pointers are -1; having exactly one child does not make it a leaf.

Hint 3

Since node values can be negative, you cannot prune paths based on the running sum exceeding the goal.