题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
def isSubtree(pRoot1, pRoot2):
if not pRoot2:
return True
if not pRoot1:
return False
if pRoot1 and pRoot2:
if pRoot2.val == pRoot1.val:
return isSubtree(pRoot1.left, pRoot2.left) and \
isSubtree(pRoot1.right, pRoot2.right)
return False
if pRoot1 and pRoot2:
return isSubtree(pRoot1, pRoot2) or self.HasSubtree(pRoot1.left, pRoot2) \
or self.HasSubtree(pRoot1.right, pRoot2)
还是C++快啊。同样的思路,人家就3ms