Find Mirror of a Binary Tree - Todo

Algorithm Steps

  1. Start at the root node of the binary tree.
  2. If the current node is null, return.
  3. Swap the left and right children of the current node.
  4. Recursively call the mirror function on the left subtree.
  5. Recursively call the mirror function on the right subtree.
  6. 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