Invert a binary tree (mirror it left to right) and return its root.
Visit nodes level by level and swap each node's children.
1function invertTree(root: TreeNode | null): TreeNode | null {2const queue = root ? [root] : [];3while (queue.length) {4const n = queue.shift()!;5[n.left, n.right] = [n.right, n.left];6if (n.left) queue.push(n.left);7if (n.right) queue.push(n.right);8}9return root;10}
Queue the root.
Space: play/pause · ←/→: step