SDE & MLE Prep

101. Symmetric Tree

Problem

Decide whether a binary tree is a mirror image of itself around its centre.

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

Constraints: follow-up: both recursively and iteratively.

A tree is symmetric if left and right subtrees are mirrors: mirror(a, b) = a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left).

Complexity: O(n).

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def mirror(a, b):
            if not a or not b:
                return a is b
            return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)

        return mirror(root.left, root.right)