Problem Statement

Given the roots of two binary trees p and q, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Example 1:

    2               2
1       3       1       3

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

    1       1
2               2

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

    2               1
1       1       1       2

Input: p = [1,2,1], q = [1,1,2]
Output: false

Recursive Implementation

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        """
            * While the values of p and q are equal,
              drill down recursively
            * If p and q are null, we have a leaf, return True
            * Return False for all other cases
                * p.val != q.val
                * structure differs
        """
        # T: O(N) ~ visit each node once
        # S: O(N) ~ recursive call stack
        if p and q and p.val == q.val:
            return  self.isSameTree(p.left, q.left) and \
                    self.isSameTree(p.right, q.right)
        elif not p and not q:
            return True
        else:
            return  False

Iterative Implementation

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

from collections import deque
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        """
            * Same as above
        """
        queue = deque([(p, q)])

        while queue:
            p, q = queue.popleft()

            if p and q and p.val == q.val:
                # Traverse tree while values and 
                # strcture are equal
                queue.append((p.left, q.left))
                queue.append((p.right, q.right))
            elif not p and not q:
                # We have found a leaf. 
                # No new information here.
                pass
            else:
                # Either the values of p and q
                # turned out to be different or
                # the structure differed
                return False
            
        return True

Leetcode 100 Same Tree