0
0
DSA Goprogramming~3 mins

Why Mirror a Binary Tree in DSA Go?

Choose your learning style9 modes available
The Big Idea

What if you could flip an entire tree upside down with just a few lines of code?

The Scenario

Imagine you have a family tree drawn on paper. Now, you want to see how it looks if you flip it like a mirror image. Doing this by redrawing every branch and connection by hand is tiring and easy to mess up.

The Problem

Manually flipping each branch means you must carefully swap every left and right child for all nodes. This is slow, confusing, and you might forget some branches or swap incorrectly, leading to mistakes.

The Solution

Mirroring a binary tree with code swaps the left and right children of every node automatically. This simple process repeats for all nodes, giving you the mirror image quickly and without errors.

Before vs After
Before
func mirrorTree(node *Node) {
  if node == nil {
    return
  }
  // Manually swap left and right for each node
  temp := node.left
  node.left = node.right
  node.right = temp
  mirrorTree(node.left)
  mirrorTree(node.right)
}
After
func mirrorTree(node *Node) {
  if node == nil {
    return
  }
  node.left, node.right = node.right, node.left
  mirrorTree(node.left)
  mirrorTree(node.right)
}
What It Enables

This lets you quickly transform any tree structure into its mirror image, enabling new ways to analyze or visualize data.

Real Life Example

In graphics or game development, mirroring a scene graph (a tree of objects) helps create reflections or symmetrical designs easily.

Key Takeaways

Manual flipping is slow and error-prone.

Code swaps children recursively for a perfect mirror.

Enables quick, reliable tree transformations.