Problem Statement in English

You’re given the root of a binary tree. Check whether it is a mirror of itself (i.e., symmetric around its center).


Approach

You could solve this by storing the tree as a list, or you can do it on the fly by comparing the left and right subtrees.

The key idea is that in the left subtree, the left child of a node should be equal to the right child of the corresponding node in the right subtree, and vice versa.

I’d recommend taking a look at the ‘concise approach’ below, which is a recursive solution that compares the left and right subtrees directly.


Solution in Python

  • Iterative Approach

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        temp = [root]

        while temp:
            q = deque(temp)
            temp = []

            while q:
                node = q.popleft()

                if not node:
                    continue

                temp.append(node.left)
                temp.append(node.right)

            if len(temp) % 2 != 0:
                return False

            l, r = 0, len(temp) - 1

            while l < r:
                lNone = temp[l] == None
                rNone = temp[r] == None

                if (lNone or rNone) and not (
                    lNone and rNone
                ):
                    return False
                elif (lNone and rNone) or (
                    temp[l].val == temp[r].val
                ):
                    l += 1
                    r -= 1
                else:
                    return False

        return True
  • Recursive Approach

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        leftAns = []
        rightAns = []

        def left(node: Optional[TreeNode]):
            if node:
                left(node.left)
                left(node.right)
            leftAns.append(None if not node else node.val)

        def right(node: Optional[TreeNode]):
            if node:
                right(node.right)
                right(node.left)
            rightAns.append(None if not node else node.val)

        left(root.left) # type: ignore
        right(root.right) # type: ignore

        if leftAns == rightAns:
            return True
        else:
            return False
  • Concise Approach

class Solution:
    def isSymmetric(self, root: TreeNode | None) -> bool:
        def solve(n1, n2):
            if not n1 or not n2:
                return n1 == n2

            return n1.val == n2.val and solve(n1.left, n2.right) and solve(n1.right, n2.left)

        return solve(root.left, root.right)

Complexity

  • Time: $O(n)$
    Since we are traversing the entire tree, the time complexity is equal to the number of nodes in the tree.

  • Space: $O(h)$
    Since we are using recursion, the space complexity is equal to the height of the tree. In the worst case, the height of the tree can be equal to the number of nodes in the tree.


And we are done.