Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree - Problem

Given a binary tree where each path going from the root to any leaf forms 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.

The goal is to determine if there exists a root-to-leaf path in the binary tree where the sequence of node values exactly matches the given array.

Input & Output

Example 1 — Valid Path Exists
$ Input: root = [0,1,0,1,null,6,1], arr = [0,1,1]
Output: true
💡 Note: The path 0 → 1 → 1 exists in the tree: starting from root(0), go left to node(1), then left again to leaf(1). This matches the sequence [0,1,1].
Example 2 — Path Exists But Not to Leaf
$ Input: root = [0,1,0,1,null,6,1], arr = [0,1]
Output: false
💡 Note: While the sequence [0,1] exists in the tree (root → left child), it doesn't end at a leaf node. The path must go from root to a leaf.
Example 3 — No Matching Path
$ Input: root = [0,1,0,1,null,6,1], arr = [0,0,1]
Output: true
💡 Note: The path 0 → 0 → 1 exists: from root(0), go right to node(0), then right again to leaf(1). This matches [0,0,1].

Constraints

  • 1 ≤ nodes.length ≤ 5000
  • 0 ≤ Node.val ≤ 9
  • 1 ≤ arr.length ≤ 5000
  • 0 ≤ arr[i] ≤ 9

Visualization

Tap to expand
Valid Sequence Check: Does [0,1,1] exist as root-to-leaf path?010161✓ Valid Path Found0 → 1 → 1Target Sequence: [0, 1, 1]011All Root-to-Leaf Paths:Path 1: [0, 1, 1] ✓ MATCH!Path 2: [0, 0, 6]Path 3: [0, 0, 1]Result: true✓ Sequence [0,1,1] exists as a complete root-to-leaf path
Understanding the Visualization
1
Input Tree & Target
Binary tree [0,1,0,1,null,6,1] and sequence [0,1,1]
2
Path Matching
Find root-to-leaf paths that match the sequence exactly
3
Result
Return true if any complete path matches the target sequence
Key Takeaway
🎯 Key Insight: Use DFS with early termination to efficiently check if target sequence exists as complete root-to-leaf path
Asked in
Facebook 15 Amazon 12 Microsoft 8
32.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen