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 from Root to Leaf Path INPUT Binary Tree: 0 1 0 1 6 1 Green = valid path Target Array: arr 0 1 1 [0] [1] [2] ALGORITHM STEPS 1 Start DFS at Root Check root.val == arr[0] 0 == 0? OK, continue 2 Recurse Left Child Check node.val == arr[1] 1 == 1? OK, continue 3 Recurse to Leaf Check node.val == arr[2] 1 == 1? OK, is leaf! 4 Validate Complete arr exhausted at leaf Return true immediately Path Matched: 0 --> 1 --> 1 Early termination on match FINAL RESULT Valid Path Found: 0 1 0 1 Output: true Sequence [0,1,1] exists as root-to-leaf path Time: O(n), Space: O(h) Key Insight: DFS with early termination efficiently validates the sequence by checking each node value against the corresponding array index. The recursion terminates early when: (1) values mismatch, or (2) array is exhausted at a leaf node (success), preventing unnecessary exploration of branches. TutorialsPoint - Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree | Optimized DFS with Early Termination
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