class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } function mirror(root) { if (!root) return null; const left = mirror(root.left); const right = mirror(root.right); root.left = right; root.right = left; return root; } // Tree: // 1 // / \ // 2 3 // / \ // 4 5 const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.right.right = new Node(5); mirror(root); function printTree(node) { if (!node) return "null"; return `${node.value} -> (${printTree(node.left)}, ${printTree(node.right)})`; } console.log(printTree(root));
The mirror function swaps the left and right children recursively. The original left subtree becomes the right subtree and vice versa. The printed output shows the root node value, then its left and right subtrees recursively.
Mirroring a binary tree means swapping the left and right children of every node recursively. This changes the structure but keeps the node values intact.
function mirror(root) {
if (!root) return;
mirror(root.left);
mirror(root.right);
let temp = root.left;
root.left = root.right;
root.right = temp;
}
// Tree setup omitted for brevity
The function correctly swaps left and right children after recursively mirroring subtrees. It does not return anything but modifies the tree in place, which is valid.
class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } function mirror(root) { if (!root) return null; const left = mirror(root.left); const right = mirror(root.right); root.left = right; root.right = left; return root; } // Tree: // 10 // / \ // 5 15 // / \ / \ // 3 7 12 20 const root = new Node(10); root.left = new Node(5); root.right = new Node(15); root.left.left = new Node(3); root.left.right = new Node(7); root.right.left = new Node(12); root.right.right = new Node(20); mirror(root); function printTree(node) { if (!node) return "null"; return `${node.value} -> (${printTree(node.left)}, ${printTree(node.right)})`; } console.log(printTree(root));
The mirror function swaps left and right children recursively. The original left subtree rooted at 5 becomes the right subtree, and the right subtree rooted at 15 becomes the left subtree, with their children swapped similarly.
Mirroring swaps left and right children. Doing it twice swaps them back, restoring the original tree structure.