Invert a binary tree
Swap the left and right child at every node to produce the mirror image of the tree.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Inverting a tree means every node's left and right subtrees trade places, all the way down. Recurse into both children first, then swap the two child references at the current node. Once every node has done this swap, the whole tree is a mirror image of the original.
Code
public static TreeNode Invert(TreeNode node) {
if (node == null) return null;
TreeNode left = Invert(node.left);
TreeNode right = Invert(node.right);
node.left = right;
node.right = left;
return node;
}static TreeNode invert(TreeNode node) {
if (node == null) return null;
TreeNode left = invert(node.left);
TreeNode right = invert(node.right);
node.left = right;
node.right = left;
return node;
}TreeNode* invert(TreeNode* node) {
if (!node) return nullptr;
TreeNode* left = invert(node->left);
TreeNode* right = invert(node->right);
node->left = right;
node->right = left;
return node;
}def invert(node: TreeNode | None) -> TreeNode | None:
if node is None: return None
left = invert(node.left)
right = invert(node.right)
node.left = right
node.right = left
return nodeTips
- The swap can happen before or after the recursive calls; the result is the same either way.
In the .NET library
This exact "swap children recursively" shape also mirrors an expression tree, and is the inverse operation used when checking whether a tree is symmetric.