KatInterview

Verify Root-to-Leaf Sequence in Binary Tree

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphstrees-graphstreearray

Last 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.
  • val is the integer value stored at node i.
  • left_index and right_index are the 0-based indices of the left and right children in nodes, or None if the child does not exist.
  • parent_index is the index of the node's parent, or None if 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:

  1. The first element of sequence matches the root node's value.
  2. Every consecutive pair of numbers sequence[k] and sequence[k+1] corresponds to a direct parent-to-child transition in the binary tree.
  3. The final element of sequence corresponds 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.