Problem statement

https://binarysearch.com/problems/Swappable-Trees/

Solution

Equal to Leetcode 0951. Flip Equivalent Binary Trees

Complexity

It is O(n + m) for time and O(max(h1, h2)) for space.

Code

class Solution:
    def solve(self, root1, root2):
        if not root1 and not root2: return True
        if (root1 and not root2) or (root2 and not root1): return False
        
        if root1.val != root2.val: return False
        
        if self.solve(root1.left, root2.left) and self.solve(root1.right, root2.right):
            return True
        
        if self.solve(root1.left, root2.right) and self.solve(root1.right, root2.left):
            return True
        
        return False