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].
Solutions
Solution 1
1 2 3 4 5 6 7 8 910111213141516
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defisValidSequence(self,root:TreeNode,arr:List[int])->bool:defdfs(root,u):ifrootisNoneorroot.val!=arr[u]:returnFalseifu==len(arr)-1:returnroot.leftisNoneandroot.rightisNonereturndfs(root.left,u+1)ordfs(root.right,u+1)returndfs(root,0)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcisValidSequence(root*TreeNode,arr[]int)bool{vardfsfunc(root*TreeNode,uint)booldfs=func(root*TreeNode,uint)bool{ifroot==nil||root.Val!=arr[u]{returnfalse}ifu==len(arr)-1{returnroot.Left==nil&&root.Right==nil}returndfs(root.Left,u+1)||dfs(root.Right,u+1)}returndfs(root,0)}