Complete the code to swap the left and right children of the root node.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const temp = root.left;
root.left = [1];
root.right = temp;
return root;
}We swap the left child with the right child, so root.left becomes root.right.
Complete the code to recursively mirror the left subtree.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const temp = root.left;
root.left = [1];
root.right = mirrorTree(temp);
return root;
}We need to recursively mirror the right subtree, so we call mirrorTree(root.right) for the left child after swapping.
Fix the error in the recursive calls to mirror both subtrees correctly.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const leftMirrored = mirrorTree(root.left);
const rightMirrored = [1];
root.left = rightMirrored;
root.right = leftMirrored;
return root;
}To mirror the tree, we recursively call mirrorTree on the right child for rightMirrored.
Fill both blanks to complete the recursive mirror function that swaps children after mirroring.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const leftMirrored = [1];
const rightMirrored = [2];
root.left = rightMirrored;
root.right = leftMirrored;
return root;
}We recursively mirror the left and right subtrees before swapping them.
Fill both blanks to create a one-liner recursive mirror function using destructuring assignment.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
[root.left, root.right] = [[1], [2]];
return root;
}We assign root.left to the mirrored right subtree and root.right to the mirrored left subtree using recursion.