检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。
如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。
解题思路:
递归判断 - > 两棵树是否相同,如不同,t1的子树与t2是否相同
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool:
def isSameTree(t1,t2):
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return t1.val==t2.val and isSameTree(t1.left,t2.left) and isSameTree(t1.right,t2.right)
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return isSameTree(t1,t2) or self.checkSubTree(t1.left,t2) or self.checkSubTree(t1.right,t2)