class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function mirrorTree(root) {
if (root === null) return null; // base case: empty node
// swap left and right children
const temp = root.left;
root.left = root.right;
root.right = temp;
// recursively mirror left subtree
mirrorTree(root.left);
// recursively mirror right subtree
mirrorTree(root.right);
return root;
}
// Driver code to build tree and test
const root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, new TreeNode(6), new TreeNode(7))
);
mirrorTree(root);
function printTree(node) {
if (!node) return "null";
const left = printTree(node.left);
const right = printTree(node.right);
return `${node.val} -> (${left}, ${right})`;
}
console.log(printTree(root));if (root === null) return null; // base case: empty node
stop recursion when node is empty
const temp = root.left;
root.left = root.right;
root.right = temp;
swap left and right children of current node
recursively mirror left subtree (which was originally right subtree)
recursively mirror right subtree (which was originally left subtree)
1 -> (3 -> (7 -> (null, null), 6 -> (null, null)), 2 -> (5 -> (null, null), 4 -> (null, null)))