题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here if pRoot1 == None or pRoot2 == None: return False #根据题干要求返回False result = False if pRoot1.val == pRoot2.val: result = self.isSubtree(pRoot1, pRoot2) #如果结点相等,isSubtree函数负责判断#这两个结点的孩子是否相等 if result == False:#当与小树相同的子树不在根部,找大树左子树 #左边找到了就不需要再找了 result = self.HasSubtree(pRoot1.left, pRoot2) | self.HasSubtree(pRoot1.right, pRoot2) return result def isSubtree(self, root1, root2): if root2 == None: return True if root1 == None: return False if root1.val == root2.val: return self.isSubtree(root1.left, root2.left) & self.isSubtree(root1.right, root2.right) return False