Skip to content

101. Symmetric Tree

Problem

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true

Solve

BFS on both side

O(n)

Quite tricky, the way is keeping track of all node to travel and their corresponded mirror position

# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
        queue = [(root, root)]
        while len(queue) > 0:
            p, q = queue.pop(0)
            if p.val != q.val:
                return False

            if p.right and q.left:
                queue.append((p.right, q.left))
            elif p.right or q.left:
                return False

            if p.left and q.right:
                queue.append((p.left, q.right))
            elif p.left or q.right:
                return False
        return True

Last update : September 17, 2023
Created : August 16, 2023