0
0
DSA Javascriptprogramming~3 mins

Why Mirror a Binary Tree in DSA Javascript?

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 swapping left and right children manually.

The Problem

Manually swapping each left and right child is slow and easy to mess up, especially for big trees. You might forget a node or swap incorrectly, causing confusion and errors.

The Solution

Mirroring a binary tree with code automatically swaps left and right children at every node, quickly and correctly. This saves time and avoids mistakes, even for large trees.

Before vs After
Before
function mirrorTree(node) {
  // manually swap left and right for each node
  if (node) {
    let temp = node.left;
    node.left = node.right;
    node.right = temp;
    mirrorTree(node.left);
    mirrorTree(node.right);
  }
}
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 transform any binary tree into its mirror image, enabling easy visualization and solving problems that require tree symmetry.

Real Life Example

In graphics or game development, mirroring a scene graph (a tree structure) helps create reflections or symmetrical effects automatically.

Key Takeaways

Manual swapping is slow and error-prone.

Code-based mirroring swaps children recursively and correctly.

Mirroring enables quick tree transformations and symmetry checks.