What if you could flip a whole tree upside down with just a few lines of code?
Why Mirror a Binary Tree in DSA Javascript?
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.
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.
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.
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);
}
}function mirrorTree(node) {
if (!node) return null;
[node.left, node.right] = [mirrorTree(node.right), mirrorTree(node.left)];
return node;
}This lets you quickly transform any binary tree into its mirror image, enabling easy visualization and solving problems that require tree symmetry.
In graphics or game development, mirroring a scene graph (a tree structure) helps create reflections or symmetrical effects automatically.
Manual swapping is slow and error-prone.
Code-based mirroring swaps children recursively and correctly.
Mirroring enables quick tree transformations and symmetry checks.