1 树的子结构

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:

    def is_same(self, pRoot1: TreeNode, pRoot2: TreeNode):
        if pRoot2 is None:
            return True
        if pRoot1 is None:
            return False
        
        return pRoot1.val == pRoot2.val and self.is_same(pRoot1.left, pRoot2.left) and self.is_same(pRoot1.right, pRoot2.right)

    def isSubStructure(self, pRoot1: TreeNode, pRoot2: TreeNode) -> bool:
        if pRoot2 is None or pRoot1 is None:
            return False
        flag = self.is_same(pRoot1, pRoot2)  # is_same()  头节点为起始节点
        return flag or self.isSubStructure(pRoot1.left, pRoot2) or self.isSubStructure(pRoot1.right, pRoot2)
View Code