Iterative method to check if two trees are mirror of each other | Utility function to create and return a new node for a binary tree ; function to check whether the two binary trees are mirrors of each other or not ; iterative inorder traversal of 1 st tree and reverse inoder traversal of 2 nd tree ; if the corresponding nodes in the two traversal have different data values , then they are not mirrors of each other . ; if at any point one root becomes None and the other root is not None , then they are not mirrors . This condition verifies that structures of tree are mirrors of each other . ; we have visited the node and its left subtree . Now , it ' s ▁ right ▁ subtree ' s turn ; we have visited the node and its right subtree . Now , it ' s ▁ left ▁ subtree ' s turn ; both the trees have been completely traversed ; tress are mirrors of each other ; Driver Code ; 1 st binary tree formation 1 ; / \ ; 3 2 ; / \ ; 5 4 ; 2 nd binary tree formation 1 ; / \ ; 2 3 ; / \ ; 4 5 ; function cal
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def areMirrors ( root1 , root2 ) : NEW_LINE INDENT st1 = [ ] NEW_LINE st2 = [ ] NEW_LINE while ( 1 ) : NEW_LINE INDENT while ( root1 and root2 ) : NEW_LINE INDENT if ( root1 . data != root2 . data ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT st1 . append ( root1 ) NEW_LINE st2 . append ( root2 ) NEW_LINE root1 = root1 . left NEW_LINE root2 = root2 . right NEW_LINE DEDENT if ( not ( root1 == None and root2 == None ) ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT if ( not len ( st1 ) == 0 and not len ( st2 ) == 0 ) : NEW_LINE INDENT root1 = st1 [ - 1 ] NEW_LINE root2 = st2 [ - 1 ] NEW_LINE st1 . pop ( - 1 ) NEW_LINE st2 . pop ( - 1 ) NEW_LINE root1 = root1 . right NEW_LINE root2 = root2 . left NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 1 ) NEW_LINE root1 . left = newNode ( 3 ) NEW_LINE root1 . right = newNode ( 2 ) NEW_LINE root1 . right . left = newNode ( 5 ) NEW_LINE root1 . right . right = newNode ( 4 ) NEW_LINE root2 = newNode ( 1 ) NEW_LINE root2 . left = newNode ( 2 ) NEW_LINE root2 . right = newNode ( 3 ) NEW_LINE root2 . left . left = newNode ( 4 ) NEW_LINE root2 . left . right = newNode ( 5 ) NEW_LINE print ( areMirrors ( root1 , root2 ) ) NEW_LINE DEDENT