Root-to-Leaf Sum Verification
Trees & GraphsAuto-graded · 23 test casesLast 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
-1or 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires checking whether any complete root-to-leaf path sums to the target value. We use iterative depth-first search with an explicit stack to handle potentially deep trees without hitting recursion limits.
The core strategy is to maintain a running sum as we traverse from the root toward the leaves. For each node we visit, we:
- Calculate the total sum from the root through this node by adding the current node's value to the accumulated sum from its ancestors
- Check if this node is a leaf (both child indices are
-1) - If it's a leaf and the sum matches the goal, return
Trueimmediately - If it's not a leaf, add its children to the stack with the updated sum for further exploration
- If we exhaust all nodes without finding a match, return
False
The algorithm correctly handles several edge cases:
- Empty tree: Returns
Falseimmediately since there are no paths - Single-node tree: Correctly identifies it as a leaf and checks if its value equals the goal
- Nodes with one child: Not treated as leaves, so they never trigger the sum check
- Negative values: No pruning based on sum magnitude, so paths can decrease and then increase again
We push the right child before the left child so that the left subtree is explored first (though exploration order doesn't affect correctness).
Complexity
Time complexity: O(n) where n is the number of nodes. Each node is visited exactly once, pushed onto the stack once, and popped once. The work per node is constant.
Space complexity: O(h) where h is the tree height, representing the maximum stack depth during traversal. In the worst case of a completely skewed tree, this becomes O(n). Using an iterative approach with an explicit stack avoids Python's default recursion limit issues with deep trees.
Solution
from typing import List, Optional
def root_to_leaf_sum_exists(root: Optional[List[tuple]], goal: int) -> bool:
if not root:
return False
stack = [(0, 0)]
while stack:
index, accumulated = stack.pop()
value, left, right = root[index]
current_sum = accumulated + value
if left == -1 and right == -1:
if current_sum == goal:
return True
continue
if right != -1:
stack.append((right, current_sum))
if left != -1:
stack.append((left, current_sum))
return False