912. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

Determine whether a given string is a valid sequence in a binary tree where any path from the root to any leaf forms a valid sequence.

Concatenating all of the node values along a path yields a sequence in the provided binary tree, and concatenating an array of integers yields the given text.

Example 1:

Input : root = [0,1,0,0,1,0,0,0,1,0,0] , arr = [0,1,0,1]

Output : true

Explanation:

The path 0 → 1 → 0 → 1 is a valid sequence (highlighted in the figure).

Other valid sequences in this tree include:

  • 0 → 1 → 0 → 1
  • 0 → 0 → 0

These sequences are valid but are not relevant to the given array.

Example 2:

Input : root = [0,1,0,0,1,0,0,0,1,0,0], arr = [0,0,1]

Output : false

Explanation:

The path 0 → 0 → 1 does not exist, therefore it is not even a valid sequence.

Now Your Turn!

Pick the correct output for the given input

Input : root = [0,1,0,0,1,0,0,0,1,0,0], arr = [0,1,1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= arr.length <= 5000
  • 0 <= arr[i] <= 9
  • Each node's value is between [0 - 9].

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
bool isValidSequence(TreeNode* root, vector<int>& arr) {
//your code goes here
}
};
Test Case

Input:

Arr
Root