题解 | #树的子结构#
树的子结构
http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def checkTree(self, root1,root2): if root2==None: return True if root1==None and root2==None: return True if root1==None and root2!=None: return False if root1.val!=root2.val: return False if root1.val==root2.val: return self.checkTree(root1.left, root2.left) and self.checkTree(root1.right, root2.right) def HasSubtree(self, pRoot1, pRoot2): if (not pRoot1)&nbs***bsp;(not pRoot2): return False if self.checkTree(pRoot1, pRoot2)==True: return True while pRoot1!=None: flag=self.checkTree(pRoot1.left,pRoot2)&nbs***bsp;self.checkTree(pRoot1.right,pRoot2) if flag==True: return True pRoot1=pRoot1.left return False