1367. Linked List in Binary Tree
https://leetcode.com/problems/linked-list-in-binary-tree/
Last updated
Was this helpful?
https://leetcode.com/problems/linked-list-in-binary-tree/
Last updated
Was this helpful?
Given a binary tree root
and a linked list with head
as the first node.
Return True if all the elements in the linked list starting from the head
correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= node.val <= 100
for each node in the linked list and binary tree.
The given linked list will contain between 1
and 100
nodes.
The given binary tree will contain between 1
and 2500
nodes.
给定linked list和二叉树,问二叉树中是否存在向下的path和list的值相等。类似字符串匹配的问题,可以主函数做分治并用另一个dfs函数对当前子树做list匹配,时间复杂度O(N * M)。注意另一个用于匹配的dfs不能少,写成以下是错的:
问题在与当head->val != root->val时匹配没有及时返回,如l = [1,2,6] t = [1,4,2,6]时当4和2不等时依然会继续往下分治,而后面是能匹配上的因此整体会错误的返回true。
生成dp数组后遍历树并做匹配,当不满足后把当前已匹配的看作suffix,把待匹配往前移动到对应prefix位置。时间复杂度O(N)。
思路参考自lee251。
做串匹配还可以KMP,KMP本质可看作是dp,dp[i]存以pattern字符串A中以i为底可匹配的最长前后缀长度。ptr初始为dp[i -1],当A[i]和dp[ptr]不等时,ptr = dp[ptr],直到相等或ptr == 0。比如aacaad的dp = [0,1,0,1,2,0],匹配d时先检查d和c是否相等,对应aac和aad;不等时往前跳到下一个与A[i-1]匹配的位置,匹配a和d,对应aa和ad。过程如下,方块为未知i,△为prefix中下一个和A[i]匹配的字符: