【剑指offer】树的子结构(python)

  1. 遍历二叉树A,如果有和二叉树B相同的结点,再进行进一步判断。
  2. 进一步判断结构是否相同。如果结点值相同,递归判断它们各自的左右结点值是不是相同。递归终止条件是到达了树A或树B的叶节点。如果树B为空,遍历完了,说明是树A的子树,如果树A为空,说明树B结构大于树A,在树A中不存在。
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def DefineResult(self,A,B):
        if not B: return True
        if not A: return False
        if A.val != B.val:
            return False
        return self.DefineResult(A.left, B.left) and self.DefineResult(A.right, B.right)
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        result = False
        if pRoot1 and pRoot2:
            if pRoot1.val == pRoot2.val:
                result = self.DefineResult(pRoot1, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.left, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.right, pRoot2)
        return result