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

Question

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

Example 1:

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

Example 2:

Machine Learning Projects
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)

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 521

Leave a Reply

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