class Solution:
def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
if not root1 or not root2:
return not root1 and not root2
if root1.val != root2.val:
return False
# 不翻转
if self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right):
return True
# 翻转
if self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left):
return True
# 不管翻转还是不翻转都不行,直接返回 False
return False
class Solution:
@lru_cache(None)
def isScramble(self, s1: str, s2: str) -> bool:
if s1 == s2:
return True
# 剪枝
if collections.Counter(s1) != collections.Counter(s2):
return False
# 枚举所有可能的根节点
for i in range(1, len(s1)):
# ----|-
# -|----
# 不进行翻转
if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):
return True
# 进行翻转
if self.isScramble(s1[i:], s2[:-i]) and self.isScramble(s1[:i], s2[-i:]):
return True
# 不管翻转还是不翻转都不行,直接返回 False
return False