3. What is the output of the following code that mirrors a binary tree?
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function mirror(node) {
if (!node) return null;
let left = mirror(node.left);
let right = mirror(node.right);
node.left = right;
node.right = left;
return node;
}
// Tree before mirroring:
// 1
// / \
// 2 3
// / \
// 4 5
let 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.val + ' -> ' + printTree(node.left) + ', ' + printTree(node.right);
}
console.log(printTree(root));