Invert a binary tree
Easy TimeO(n) SpaceO(h)
Inverting a tree mirrors it: every node's left and right children change places, all the way down, so the tree comes back as its own reflection. Given the root of one, invert it and return the root. The swap applies at every node, not only at the root; the existing nodes are re-pointed rather than a new tree built; and an empty tree inverts to an empty tree.
Examples
Example 1
- Input
- node = invert(buildTree())out = []
- Output
- Read root first, the mirrored tree is
[4,7,9,6,2,3,1]4, then7, 9, 6, then2, 3, 1.
Example 2
- Input
- node = buildTree()out = []
- Output
- The same tree before inverting — every pair of children now in the opposite order.
[4,2,1,3,7,6,9]
The Code
function buildTree() {
return {
val: 4,
left: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } },
right: { val: 7, left: { val: 6, left: null, right: null }, right: { val: 9, left: null, right: null } }
};
}
function invert(node) {
if (node === null) return null;
const left = invert(node.left);
const right = invert(node.right);
node.left = right;
node.right = left;
return node;
}
function flatten(node, out) {
if (node === null) return out;
out.push(node.val);
flatten(node.left, out);
flatten(node.right, out);
return out;
}
flatten(invert(buildTree()), []);Done
The first 9 calls, of 31. This one does not fit on a page.
More like this
All binary trees examples (9) →- Inorder traversal Left subtree, then the node, then right — a BST comes out sorted.
- Max tree depth A node is one deeper than its deepest child.
- Validate a BST Every node needs a valid range, not just a valid parent.
- Level order (BFS) Process a whole row, collecting the next one as you go.
- Lowest common ancestor Walk down until the two targets fall on opposite sides.
- Tree diameter Each node returns a depth upward while quietly recording a width.