说明:
两种方法:
方法1:
对于t1的每棵子树,都去判断是否与t2树的拓扑结构完全一样,这个过程的实践复杂度是O(M),t1的子树共有N棵,所以时间复杂度为O(M*N)
方法2:
首先把t1树和t2树按照先序遍历的方式序列化,之后用KMP算法去判断t2Str是否是t1Str的子串即可。t1的序列化的过程是O(N),t2的序列化是O(M),KMP算法解决匹配问题的复杂度是O(M+N),所以总体时间复杂度是O(M+N)
#方法1的实现
def isSubTopoBST2(t1, t2):
def isTopoBST2(t1, t2):
if not t1 and not t2:
return True
if not t1 or not t2 or t1.val != t2.val:
return False
return isTopoBST2(t1.left, t2.left) and isTopoBST2(t1.right, t2.right)
if not t1 or not t2:
return False
return isTopoBST2(t1, t2) or isSubTopoBST2(t1.left, t2) or isSubTopoBST2(t1.right, t2)
#方法2的实现
def isSubTopoBST(t1, t2):
def serialTreeByPre(root):
if not root:
return '#!'
res = root.val + '!'
res += serialTreeByPre(root.left)
res += serialTreeByPre(root.right)
return res
def isTopoBST(s, m):
if not s or not m or len(s) < len(m) or len(m) < 1:
return False
mi = 0
si = 0
nextarr = getNextArray(m)
while mi < len(m) and si < len(s):
if s[si] == m[mi]:
mi += 1
si += 1
elif nextarr[mi] == -1:
si += 1
else:
mi = nextarr[mi]
if mi == len(m):
return True
else:
return False
def getNextArray(m):
if len(m) == 1:
return -1
nextarr = [None for i in range(len(m))]
nextarr[0] = -1
nextarr[1] = 0
pos = 2
cn = 0
while pos < len(m):
if m[pos-1] == m[cn]:
nextarr[pos] = cn + 1
pos += 1
cn += 1
elif cn > 0:
cn = nextarr[cn]
else:
nextarr[pos] = 0
pos += 1
return nextarr
if not t1 or not t2:
return False
str1 = serialTreeByPre(t1)
str2 = serialTreeByPre(t2)
arr1 = str1.split('!')
arr1.pop()
arr2 = str2.split('!')
arr2.pop()
return isTopoBST(arr1, arr2)