Algorithm Steps
- Start at the
root
node of the binary tree. - If the current node is
null
, return. - Swap the
left
andright
children of the current node. - Recursively call the mirror function on the
left
subtree. - Recursively call the mirror function on the
right
subtree. - The binary tree is now mirrored.
Find Mirror of a Binary Tree - 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 mirror(root):
if root is None:
return
root.left, root.right = root.right, root.left
mirror(root.left)
mirror(root.right)
return root
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / / \
# 4 5 6
root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, TreeNode(5), TreeNode(6)))
mirror(root)
# The tree is now transformed into its mirror image