给定彼此独立的两棵二叉树,树上的节点值两两不同,判断 t1 树是否有与 t2 树完全相同的子树。
子树指一棵树的某个节点的全部后继节点
数据范围:树的节点数满足
,树上每个节点的值一定在32位整型范围内
进阶:空间复杂度:
,时间复杂度
class Solution: def isContains(self , root1: TreeNode, root2: TreeNode) -> bool: def dfs_same(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False l, r = dfs_same(t1.left, t2.left), dfs_same(t1.right, t2.right) return l and r and t1.val == t2.val def dfs(x): if not x: return not root2 return dfs_same(x, root2) or dfs(x.left) or dfs(x.right) return dfs(root1)
class Solution: def isContains(self , t1: TreeNode, t2: TreeNode) -> bool: # write code here if not t1 and t2: return False if not t2 and t1: return False if not t2 and not t1: return True if t1.val==t2.val: return self.isContains(t1.left, t2.left) and self.isContains(t1.right, t2.right) else: return self.isContains(t1.left, t2)&nbs***bsp;self.isContains(t1.right, t2)
class Solution: def isContains(self , root1 , root2 ): # write code here if not root1: return False if not root2: return True self.res = False def dfs(root1, root2): if not root1: return if root1.val == root2.val: if self.process(root1, root2): self.res = True return dfs(root1.left, root2) dfs(root1.right, root2) dfs(root1, root2) return self.res def process(self, root1, root2): if root1 == None and root2 == None: return True if root1 == None and root2 != None: return False if root1 != None and root2 == None: return False if root1.val == root2.val: return self.process(root1.left, root2.left) and self.process(root1.right, root2.right) else: return False