Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree Problem
Description
LeetCode Problem 1430.
Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.
Example 1:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation:
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure).
Other valid sequences are:
0 -> 1 -> 1 -> 0
0 -> 0 -> 0
Example 2:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.
Example 3:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.
Constraints:
1 <= arr.length <= 50000 <= arr[i] <= 9- Each node's value is between [0 - 9].
Solution
Approach: Depth-First Search Along the Array
Walk down the tree and the array together. dfs(node, i) answers: is there a path from node down to a leaf that spells arr[i], arr[i + 1], ..., arr[last]?
- If
nodeis null ornode.val != arr[i], the answer is no. - If
iis the last index, the values match, and the path must end here, so the answer is yes only ifnodeis a leaf. - Otherwise continue with
dfs(node.left, i + 1)ordfs(node.right, i + 1).
The leaf check is the tricky part: in Example 3, 0 -> 1 -> 1 matches values all the way, but the last node still has children, so it is not a valid sequence. The reverse also fails naturally: if the array is longer than the path, we reach a null child and return false.
The search never goes deeper than arr.length, and a branch stops as soon as a value differs.
Complexity: O(N) time in the worst case, where N is the number of nodes (only nodes within depth L are ever visited, for an array of length L), and O(L) recursion depth.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidSequence(self, root: Optional[TreeNode], arr: List[int]) -> bool:
def dfs(node: Optional[TreeNode], i: int) -> bool:
# does a path from node down to a leaf spell arr[i:]?
if node is None or node.val != arr[i]:
return False
if i == len(arr) - 1:
return node.left is None and node.right is None # the path must end at a leaf
return dfs(node.left, i + 1) or dfs(node.right, i + 1)
return dfs(root, 0)