Verify Root-to-Leaf Sequence in Binary Tree
Trees & GraphsAuto-graded · 24 test casesLast updated
Check if a list of integers forms a complete valid root-to-leaf path in a binary tree given as an adjacency table.
You are given a binary tree represented as an array of nodes, where each entry nodes[i] is a list containing [val, left_index, right_index, parent_index].
nodes[0]is always the root of the tree.valis the integer value stored at nodei.left_indexandright_indexare the 0-based indices of the left and right children innodes, orNoneif the child does not exist.parent_indexis the index of the node's parent, orNoneif it is the root.- All node values in the tree are distinct.
You are also given a list of integers sequence.
Determine whether sequence forms a valid, complete path starting at the root and terminating at a leaf node.
A path is considered valid if and only if:
- The first element of
sequencematches the root node's value. - Every consecutive pair of numbers
sequence[k]andsequence[k+1]corresponds to a direct parent-to-child transition in the binary tree. - The final element of
sequencecorresponds to a leaf node (a node with no left or right child).
Return True if the path is valid according to these rules, and False otherwise.
Constraints
- $1 \le \text{len}(nodes) \le 10^5$
- $1 \le \text{len}(sequence) \le 10^5$
- Node values in the tree are unique integers.
nodes[0]is guaranteed to be the root.
Examples
Example 1
Input: is_valid_path([[1, 1, 2, None], [2, None, None, 0], [3, None, None, 0]], [1, 2])
Output: True
Example 2
Input: is_valid_path([[1, 1, None, None], [2, None, None, 0]], [1, 3])
Output: False
Example 3
Input: is_valid_path([[1, None, None, None]], [1])
Output: True
Example 4
Input: is_valid_path([[1, 1, None, None], [2, 2, None, 0], [4, None, None, 1]], [1, 2, 4])
Output: True
Hints
Hint 1
Do you need to process or search the entire tree, or can you simply simulate the movement step-by-step along the sequence?
Hint 2
Since node values are distinct, each parent node has at most one child matching the next target value in the sequence.
Hint 3
Don't forget to verify that the sequence ends on a leaf node—reaching an internal node at the end of the sequence is invalid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To verify if the given sequence corresponds to a valid root-to-leaf path, we can simulate walking down the tree starting from the root (index 0).
- Root Check: First, verify that
sequence[0]matchesnodes[0][0]. If it does not, the path is invalid. - Path Traversal: Maintain a reference to the current node index (
current = 0). Iterate through each subsequent value insequence:- Inspect the left child (
nodes[current][1]) and right child (nodes[current][2]). - If a child exists and its value equals the expected next sequence value, transition
currentto that child's index. - If neither child matches the next value (or if no child exists), the path cannot be followed further, so return
False.
- Inspect the left child (
- Leaf Check: After matching all values in
sequence, check if the final node atcurrentis a leaf (meaning both its left and right child indices areNone). If it is a leaf, returnTrue; otherwise, returnFalse.
Because node values are distinct, at each step there is at most one matching child, eliminating any need for backtracking or building full look-up tables.
Complexity
- Time Complexity: $O(\min(N, H))$, where $N$ is the length of
sequenceand $H$ is the height of the tree. At each step in the sequence, we perform $O(1)$ child inspections. - Space Complexity: $O(1)$ auxiliary space, as we only need a few pointers/indices to track the current state.
Python 3 Reference Solution
from typing import List, Optional
def is_valid_path(nodes: List[List[Optional[int]]], sequence: List[int]) -> bool:
if not nodes or not sequence:
return False
if sequence[0] != nodes[0][0]:
return False
current = 0
for value in sequence[1:]:
left = nodes[current][1]
right = nodes[current][2]
if left is not None and nodes[left][0] == value:
current = left
elif right is not None and nodes[right][0] == value:
current = right
else:
return False
return nodes[current][1] is None and nodes[current][2] is None