class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = val === undefined ? 0 : val; this.left = left === undefined ? null : left; this.right = right === undefined ? null : right; } } function mirrorTree(root: TreeNode | null): TreeNode | null { if (!root) return null; const left = mirrorTree(root.left); const right = mirrorTree(root.right); root.left = right; root.right = left; return root; } function inorder(root: TreeNode | null, result: number[] = []): number[] { if (!root) return result; inorder(root.left, result); result.push(root.val); inorder(root.right, result); return result; } const root = new TreeNode(1, new TreeNode(2), new TreeNode(3)); mirrorTree(root); console.log(inorder(root));
The mirrorTree function swaps the left and right children recursively. The original tree is:
1
/ \
2 3
After mirroring, it becomes:
1
/ \
3 2
Inorder traversal visits left, root, right, so the output is [3, 1, 2].
The recursive calls mirror the left and right subtrees fully before swapping them at the current node. This ensures the entire tree is mirrored correctly.
function mirrorTree(root: TreeNode | null): TreeNode | null {
if (!root) return null;
mirrorTree(root.left);
mirrorTree(root.right);
const temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
const root = new TreeNode(1, new TreeNode(2), new TreeNode(3));
mirrorTree(root);
console.log(root.left?.val);The code correctly mirrors the tree by recursively calling mirrorTree on left and right subtrees, then swapping them. The output root.left?.val is 3 after mirroring.
const root = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)), new TreeNode(7, new TreeNode(6), new TreeNode(9)) ); mirrorTree(root); console.log(inorder(root));
The original inorder traversal is [1, 2, 3, 4, 6, 7, 9]. After mirroring, the tree's left and right children are swapped at every node, reversing the inorder traversal to [9, 7, 6, 4, 3, 2, 1].
The mirrorTree function visits each node exactly once to swap its children, so the time complexity is O(n).