Given the root of a binary tree and a list of integers sequence, determine whether sequence is a subsequence of the tree's in-order traversal.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
The in-order traversal visits nodes in the order: left subtree, current node, right subtree.
Function Signature
def is_subsequence(root: Optional[TreeNode], sequence: List[int]) -> bool:
Rules
-
root
is a
TreeNode
with fields
val
,
left
and
right
. The examples write the tree as a level-order list in which
None
marks a missing child.
-
The tree is not necessarily a binary search tree, and values may repeat.
-
Each node of the traversal can match at most one element of
sequence
. Return
True
when every element of
sequence
can be matched, in order, to distinct positions of the in-order traversal, and
False
otherwise.
Constraints
-
The number of nodes in the tree is in the range
[1, 10^4]
.
-
-10^4 <= Node.val <= 10^4
-
1 <= sequence.length <= 10^4
-
-10^4 <= sequence[i] <= 10^4
Examples
Input: root = [5,3,8,1,4,7,9], sequence = [1,3,7,9]
Output: True
The tree has root 5, children 3 and 8, and leaves 1, 4, 7 and 9, so the in-order traversal is [1, 3, 4, 5, 7, 8, 9]. The values 1, 3, 7 and 9 appear in that order once 4, 5 and 8 are deleted.
Input: root = [5,3,8,1,4,7,9], sequence = [4,3]
Output: False
The traversal is again [1, 3, 4, 5, 7, 8, 9]. Both values are in the tree, but 3 comes before 4 in the traversal, and the sequence requires 4 first.
Input: root = [2,1,2], sequence = [2,2,2]
Output: False
The in-order traversal is [1, 2, 2]. Only two nodes hold the value 2, so the third 2 in the sequence has no node left to match.