0
0
DSA Typescriptprogramming~3 mins

Why Mirror a Binary Tree in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

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

The Scenario

Imagine you have a family tree drawn on paper, and you want to see its reflection as if looking in a mirror. Doing this by hand means redrawing every branch and leaf on the opposite side, which is tiring and easy to mess up.

The Problem

Manually flipping each branch and leaf is slow and prone to mistakes. You might forget to swap some parts or place them incorrectly, making the mirrored tree wrong and confusing.

The Solution

Using a simple method to swap the left and right branches of every node in the tree automatically creates the mirror image. This saves time and ensures accuracy by handling every part systematically.

Before vs After
Before
function mirrorTree(node) {
  // manually redraw each branch
  // very complex and error-prone
}
After
function mirrorTree(node) {
  if (!node) return null;
  [node.left, node.right] = [mirrorTree(node.right), mirrorTree(node.left)];
  return node;
}
What It Enables

This lets you quickly create a mirrored version of any tree, useful in graphics, data transformations, and problem-solving.

Real Life Example

In photo editing apps, flipping images horizontally is like mirroring a tree structure of pixels, making the picture look reversed instantly.

Key Takeaways

Manually mirroring a tree is slow and error-prone.

Swapping left and right children recursively automates the mirror process.

This method is fast, reliable, and easy to implement.