• 第一步在树A中查找与根节点的值一样的节点
  • 第二步是判断树A中以R为根节点的子树是不是和树B具有相同的结构
# -*- 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 self.equal(pRoot1.val,pRoot2.val):
                result = self.DoesTree1HaveTree2(pRoot1,pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.left,pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.right,pRoot2)
        return result
    def DoesTree1HaveTree2(self,pRoot1,pRoot2):
        if not pRoot2:
            return True
        if not pRoot1:
            return False
        if not self.equal(pRoot1.val,pRoot2.val):
            return False
        return self.DoesTree1HaveTree2(pRoot1.left,pRoot2.left) and self.DoesTree1HaveTree2(pRoot1.right,pRoot2.right)
    def equal(self,num1,num2):
        if -0.000001 < num1 - num2 < 0.000001:
            return True
        else:
            return False