SDE & MLE Prep

100. Same Tree

Problem

Decide whether two binary trees p and q are identical: the same shape with the same value in every corresponding node.

Example: [1,2,3] and [1,2,3] → true; [1,2] and [1,null,2] → false

Both null → true; one null or values differ → false; else recurse on both sides.

Complexity: O(n).

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p or not q:
            return p is q
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)