Problem statement

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

Solution

Equal to leetcode 0100. Same Tree

Complexity

It is O(n) for time and space.

Code

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