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.
Input: root =[0,1,0,0,1,0,null,null,1,0,0], arr =[0,1,0,1]Output: trueExplanation: The path 0->1->0->1is a valid sequence(green color in the figure).Other valid sequences are:0->1->1->00->0->0
Example 2:
1
2
3
Input: root =[0,1,0,0,1,0,null,null,1,0,0], arr =[0,0,1]Output: falseExplanation: The path 0->0->1 does not exist, therefore it is not even a sequence.
Example 3:
1
2
3
Input: root =[0,1,0,0,1,0,null,null,1,0,0], arr =[0,1,1]Output: falseExplanation: The path 0->1->1is a sequence, but it is not a valid sequence.
Intuition:
We need to check if there exists a root-to-leaf path in the binary tree such that the sequence of node values matches the given array. This is a classic DFS problem where we match the current node’s value with the current index in the array and recursively check the left and right subtrees.
Approach:
Start DFS from the root node and index 0 of the array.
At each node:
If the node is null or the index is out of bounds, return false.
If the node’s value does not match arr[index], return false.
If at a leaf node and index is at the last element of arr, return true.
Recursively check left and right children with index + 1.