题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
解答:
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if pRoot1 is None or pRoot2 is None:
return False
flag=False
if pRoot1.val==pRoot2.val:
flag=self.SubTree(pRoot1,pRoot2)
if flag==False:
flag=self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
return flag
def SubTree(self,root1,root2):
if root2 is None:
return True
if root1 is None :
return False
if root1.val==root2.val:
return self.SubTree(root1.left,root2.left) and self.SubTree(root1.right,root2.right)
return False
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if pRoot1 is None or pRoot2 is None:
return False
flag=False
if pRoot1.val==pRoot2.val:
flag=self.SubTree(pRoot1,pRoot2)
if flag==False:
flag=self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
return flag
def SubTree(self,root1,root2):
if root2 is None:
return True
if root1 is None :
return False
if root1.val==root2.val:
return self.SubTree(root1.left,root2.left) and self.SubTree(root1.right,root2.right)
return False