Title Description
Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)
Thinking
Traversing a first tree, to find the root of the tree, and b value equal to the node, the determination is not to find the subtree.
Judgment is not subtree when the recursive method, the root node is determined, and then determines the left child and right child.
Code
# -*- 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 result = False if pRoot1 and pRoot2: if pRoot1.val == pRoot2.val: result = self.isSubtree(pRoot1,pRoot2) if not result and pRoot1.left: result = self.isSubtree(pRoot1.left,pRoot2) if not result and pRoot2.right: result = self.isSubtree(pRoot1.right,pRoot2) return result def isSubtree(self,p1,p2): if not p2: return True if not p1: return False if p1.val != p2.val: return False check_left = self.isSubtree(p1.left, p2.left) check_right = self.isSubtree(p1.right,p2.right) return check_left and check_right