Given Binary Tree is Mirror Image of Itself or Symmetric Tree
In this class, We discuss whether the Given Binary Tree is a Mirror Image of Itself or a Symmetric Tree.
Readers can prepare a full competitive coding course to crack product development companies. Click Here.
The reader should have basic coding skills to work with competitive coding. Click here.
Question:
Given a binary tree.
Our task is to check whether the binary Tree is symmetric or not.
In another way, the binary Tree is a mirror image of itself or not.
Time complexity O(N)
Space complexity: O(H) H is the height of the binary Tree.
The below diagram shows the symmetric binary tree example.
Logic:
We provided a step-by-step explanation in the video.
Code:
class Node:
# Constructor to create a new node
def __init__(self, val):
self.data = val
self.left = None
self.right = None
class Solution:
def isMirror(self,root1, root2):
if root1 is None and root2 is None:
return True
if (root1 is not None and root2 is not None):
if root1.data == root2.data:
return (self.isMirror(root1.left, root2.right)and
self.isMirror(root1.right, root2.left))
return False
def isSymmetric(self, root):
return self.isMirror(root,root)
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
ob=Solution()
z=ob.isSymmetric(root)
print(z)