Check if Two Binary Trees are Mirror Images

Algorithm Steps

  1. Given two binary trees, if both trees are empty, they are mirrors; if one is empty and the other is not, they are not mirrors.
  2. Compare the root nodes of both trees. If the values are not equal, the trees are not mirrors.
  3. Recursively check if the left subtree of the first tree is a mirror of the right subtree of the second tree, and if the right subtree of the first tree is a mirror of the left subtree of the second tree.
  4. If both recursive checks return true, then the two trees are mirror images of each other.

Check if Two Binary Trees are Mirror Images - Code Examples Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def isMirror(t1, t2):
    if not t1 and not t2:
        return True
    if not t1 or not t2:
        return False
    return (t1.val == t2.val) and isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)

# Example usage:
if __name__ == '__main__':
    # Tree 1:
    #      1
    #     / \
    #    2   3
    #
    # Tree 2 (mirror of Tree 1):
    #      1
    #     / \
    #    3   2
    tree1 = TreeNode(1, TreeNode(2), TreeNode(3))
    tree2 = TreeNode(1, TreeNode(3), TreeNode(2))
    print(isMirror(tree1, tree2))