题目链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
难度:中等
描述:
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
题解
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:def recursion(A, B):if B is None:return Trueif A is None or A.val != B.val:return Falsereturn recursion(A.left, B.left) and recursion(A.right, B.right)if A is None or B is None:return Falseelse:return recursion(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
