Check if Two Binary Trees are Mirror Images - Algorithm, Visualization, Examples
⬅ Previous TopicCheck if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
Next Topic ⮕Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
Next Topic ⮕Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
Solution
Algorithm Steps
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))