Implement binaryTreeFlip(root) that returns the mirror image of a binary tree: every node keeps its value, but its left and right children are swapped, all the way down. This is the classic Invert Binary Tree problem. A node is a plain object { val, left, right }, and an empty tree (or a missing child) is null. Return a brand-new tree and leave the input untouched.
// A node is a plain object; an empty tree or missing child is null.
type TreeNode = { val: number; left: TreeNode | null; right: TreeNode | null };
// root: the root of the tree to mirror (or null for an empty tree).
// returns: a NEW mirrored tree; the input is not mutated.
function binaryTreeFlip(root: TreeNode | null): TreeNode | null;
// A two-level tree: the children of the root swap sides.
// 1 1
// / \ → / \
// 2 3 3 2
binaryTreeFlip({
val: 1,
left: { val: 2, left: null, right: null },
right: { val: 3, left: null, right: null },
});
// → { val: 1,
// left: { val: 3, left: null, right: null },
// right: { val: 2, left: null, right: null } }
// A left-only child becomes a right-only child.
// 1 1
// / → \
// 2 2
binaryTreeFlip({
val: 1,
left: { val: 2, left: null, right: null },
right: null,
});
// → { val: 1, left: null, right: { val: 2, left: null, right: null } }
left/right on the nodes you were given. After the call, the original tree must be exactly as it was.binaryTreeFlip(null) returns null, and any missing child stays null.val is altered, added, or dropped.