# -*- 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
else:
res0 = self.HasSubtree(pRoot1.left,pRoot2)
res1 = self.HasSubtree(pRoot1.right,pRoot2)
res2 = self.isSubtree(pRoot1,pRoot2)
if res0 == True or res1 == True or res2 == True:
return True
else:
return False
def isSubtree(self,pRoot1,pRoot2):
if pRoot2 == None:
return True
if pRoot1 == None:
return False
if pRoot1.val == pRoot2.val:
res0 = self.isSubtree(pRoot1.left,pRoot2.left)
res1 = self.isSubtree(pRoot1.right,pRoot2.right)
if res0 == True and res1 == True:
return True
return False
二叉子树判定分为两个步骤,一个是判断是否节点和子树根节点重合,若重合,开始下一步:
第二步,递归判断每个子节点是不是相同,若相同,则返回Ture