这个问题可以拆分成
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubStructure(self, A, B):
"""
:type A: TreeNode
:type B: TreeNode
:rtype: bool
"""
# 只有第一次存在B为None的情况,因为之后B不会变
if A is None or B is None:
return False
# 利用队列BFS(层次遍历)判断两个树是否匹配
aQueue = [A]
bQueue = [B]
flag = True
while aQueue:
a = aQueue.pop()
b = bQueue.pop()
if b:
if a and a.val == b.val:
aQueue.append(a.left)
aQueue.append(a.right)
bQueue.append(b.left)
bQueue.append(b.right)
else:
flag = False
# 当前根结点是否匹配 or 左子树是否匹配 or 右子树是否匹配
return flag or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# 利用递归实现DFS
def isMatch(self, A, B):
if B is None:
return True
if A is None or A.val != B.val:
return False
return self.isMatch(A.left, B.left) and self.isMatch(A.right, B.right)
def isSubStructure(self, A, B):
"""
:type A: TreeNode
:type B: TreeNode
:rtype: bool
"""
if A is None or B is None:
return False
return self.isMatch(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
原文:https://www.cnblogs.com/cling-cling/p/13038992.html