Talentd
FleetCode

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

Medium47.6% acceptancePremium elsewhere, free here

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 <= 5000
  • 0 <= arr[i] <= 9
  • Each node's value is between [0 - 9].

Hints open one at a time

Hint 1
Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers.
Hint 2
When reaching at final position check if it is a leaf node.
17:32
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[0,1,0,0,1,0,null,null,1,0,0]
[0,1,0,1]
Input
[0,1,0,0,1,0,null,null,1,0,0]
[0,0,1]
Input
[0,1,0,0,1,0,null,null,1,0,0]
[0,1,1]
Your code is saved on this device.Solution