In terms of the problem itself, a binary tree can be expressed something like:
type Node<T> = { value: T, left?: Node<T>, right?: Node<T> }
function invertTree(root) { if (!root) return null; // Swap! const tmp = root.left; root.left = invertTree(root.right); root.right = invertTree(tmp); return root; };
function invertTree(root) { const stack = [root]; while (stack.length > 0) { const node = stack.pop(); if (!node) continue; // Swap! const tmp = node.right; node.right = node.left; node.left = tmp; stack.push(node.left); stack.push(node.right); } return root; }
In terms of the problem itself, a binary tree can be expressed something like:
Given a root, you can invert it recursively with some code like this: Or using an explicit stack: I think without prep would be harder to come up with the non-recursive version.