https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
思路:二叉树,递归
- B和A root节点val相同,判断B的left和A的left,B的right和A的right是否相同,若都相同则B为A的子结构
- 若B和A root节点val不同,判断B是否为A的left的子结构或B是否为A的right的子结构,如果都不是,则B不是A的子结构
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubStructureWithRoot(self, A, B):
if B is None:
return True
if A is None :
return False
return A.val == B.val and self.isSubStructureWithRoot(A.right, B.right) and self.isSubStructureWithRoot(A.left, B.left)
def isSubStructure(self, A, B):
"""
:type A: TreeNode
:type B: TreeNode
:rtype: bool
"""
if A is None or B is None:
return False
return self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B) or self.isSubStructureWithRoot(A, B)