December 17, 2021

Symmetric Tree

Problem Statement: 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,null,3,null,3]
Output: false

Constraints:

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


Asked in: Facebook Amazon ,Apple

Leetcode Difficulty: Easy

Code:
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution(object):    
    def check(self, root1, root2):
        if root1==None and root2==None: return True
        elif root1==None and root2!=None: return False
        elif root1!=None and root2==None: return False
        
        if root1.val==root2.val:
            if self.check(root1.left, root2.right) and self.check(root1.right, root2.left):
                return True
            else:
                return False
        else:
            return False
    
    def isSymmetric(self, root):
        return self.check(root, root)
Thought Process / Explanation:
This problem also follows a typical pattern like other tree problems... we check for the root node and recursively call for left and right parts of the tree. Here, since we spawn two trees,  so the left side of one should be same as the right side of one and vice-versa.


Thank You!

No comments:

Post a Comment

Please share your valuable feedback. It will help me and community grow.