题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
1 class Solution: 2 def HasSubtree(self, pRoot1, pRoot2): 3 # write code here 4 if pRoot1==None or pRoot2==None: 5 return False 6 def getEqual(pRoot1,pRoot2): 7 if pRoot2==None: 8 return True 9 if pRoot1==None: 10 return False 11 if pRoot1.val == pRoot2.val: 12 if pRoot2.left==None: 13 leftEqual=True 14 else: 15 leftEqual=getEqual(pRoot1.left,pRoot2.left) 16 if pRoot2.right==None: 17 rightEqual=True 18 else: 19 rightEqual=getEqual(pRoot1.right,pRoot2.right) 20 return leftEqual and rightEqual 21 return False 22 23 if pRoot1.val == pRoot2.val: 24 ret = getEqual(pRoot1,pRoot2) 25 if ret: 26 return True 27 ret = self.HasSubtree(pRoot1.left,pRoot2) 28 if ret: 29 return True 30 ret = self.HasSubtree(pRoot1.right,pRoot2) 31 return ret
2019-12-09 18:40:20