1629. Route by Values

Easy1.5 points estimatedBinary TreeDepth-First SearchArray

A decoder reads a binary tree of digits and needs to know whether a given code is spelled out by one of its branches. A route is a path that begins at the root, moves only from a parent to one of its children, and finishes at a leaf (a node with no children).

Given the root and an integer array seq, return true if there exists a route whose node values, read from top to bottom, are exactly equal to seq: the same length, the same values in the same order, and the last matched node must be a leaf. Matching only a prefix of a longer route, or stopping at an inner node, does not count.

Use a depth-first traversal that carries an index into seq and prunes a branch when the value differs. An explicit stack keeps long chains safe. Target complexity: O(n) time, O(n) space.

Example 1

Input:
root = [1,2,3,4], seq = [1,2,4]
Output:
true
Explanation:

The path 1, 2, 4 ends at the leaf 4 and matches seq.

Example 2

Input:
root = [1,2,3,4], seq = [1,2]
Output:
false
Explanation:

The values 1, 2 match a prefix, but node 2 is not a leaf, so the route does not count.

Example 3

Input:
root = [5], seq = [5]
Output:
true
Explanation:

A single node is a root-to-leaf path of length one.

Constraints

1 ≤ nodes ≤ 1000

1 ≤ seq.length ≤ 1000

0 ≤ Node.val, seq[i] ≤ 9

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…