1. Base case
An empty subtree mirrors to itself.
if (root === null) {
return null;
}Typorithm · easy
Step 1 of 8 · intro card
Trees
Recursively swap every node's left and right children to produce the mirror image of the tree.
Inverting a tree mirrors it left-to-right at every level.
Recurse into both children, then swap them — but save one side first so it is not lost.
The base case returns null for an empty subtree, and the post-order swap does the work.
Recurse, then swap children.
Save the left before overwriting it.
Base case: null returns null.
function invertTree(root) {
if (root === null) {
return null;
}
const left = invertTree(root.left);
root.left = invertTree(root.right);
root.right = left;
return root;
}Connect each part of the code to the concept before you type.
An empty subtree mirrors to itself.
if (root === null) {
return null;
}Capture the inverted left before overwriting it.
const left = invertTree(root.left)The inverted right subtree becomes the new left.
root.left = invertTree(root.right)The saved inverted left becomes the new right.
root.right = leftRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.