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

Table of Contents

Question

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

Example 1:

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

Example 2:

symtree2
Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

Follow up: Could you solve it both recursively and iteratively?

Python Solution

def rec(ln,rn):
    if ln==None and rn==None:
        return True
    elif ln==None or rn==None:
        return False
    if ln.val!=rn.val:
        return False
    l = rec(ln.left,rn.right)
    r = rec(ln.right,rn.left)
    
    return l and r

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        return rec(root.left,root.right)

Leave a Reply

Your email address will not be published. Required fields are marked *