![aac049a555870eac50e5c335dfddfa62.png](https://i-blog.csdnimg.cn/blog_migrate/c27a848b1ba2679038bc2ab27e44afc8.png)
思路一:dfs里面嵌套dfs,第一层dfs遍历s树,然后以当前节点代表的子树和t进行dfs判断是否相等。时间复杂度为O(s*t)
# Definition for a binary tree node.
思路二:kmp
如何更好地理解和掌握 KMP 算法? - 海纳的回答 - 知乎 https://www.zhihu.com/question/21923021/answer/281346746
从这篇讲解里面可以看出,求next数组的就是,以模式字符串为主字符串,以模式字符串的前缀为目标字符串,也就是通过这个过程就能求出主字符串前缀后缀最大的重复长度了。
# 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 = right
class Solution:
def compute_next(self,s):
Next = [0]*len(s)
i = 1
j = 0
while i < len(s):
if s[j] == s[i]:
j += 1
i += 1
if i < len(s):
Next[i] = j
else:
i += 1
j = 0
Next[0] = -1 #在下面代码里有妙用
return Next
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
#序列化s,t
tmp = []
def xulie(cur):
if not cur:
tmp.append('#')
return
tmp.append(cur.val)
xulie(cur.left)
xulie(cur.right)
xulie(s)
s = tmp
tmp = []
xulie(t)
t = tmp
Next = self.compute_next(t)
j = 0
i = 0
while i < len(s) and j <len(t):
#j==-1说明次数和t的第0位都不匹配,要把i也加1,防止死循环
if j==-1 or s[i] == t[j]:
j+=1
i+=1
else:
j = Next[j]
return j==len(t)