Invert Binary Tree

easyTrees: Traversal80 stepsJava · Python · C++

Mirror a tree: swap every node's left and right children. Swap at the current node, then invert both subtrees (or the other way round); every node gets swapped exactly once.

▶ Watch the animated trace

Traced input: root = [4, 2, 7, 1, 3, 6, 9] → [4,7,2,9,6,3,1]. Original problem: neetcode.io/problems/invert-a-binary-tree

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(h)

One swap per node; recursion depth h.

Key idea

Common mistakes

Solution

Java
TreeNode invertTree(TreeNode root) {
    if (root == null) return null;
    TreeNode tmp = root.left;
    root.left = root.right;
    root.right = tmp;
    invertTree(root.left);
    invertTree(root.right);
    return root;
}
Python
def invertTree(root: Optional[TreeNode]) -> Optional[TreeNode]:
    if not root: return None
    root.left, root.right = root.right, root.left
    invertTree(root.left)
    invertTree(root.right)
    return root
C++
TreeNode* invertTree(TreeNode* root) {
    if (!root) return nullptr;
    swap(root->left, root->right);
    invertTree(root->left);
    invertTree(root->right);
    return root;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Empty tree
Nothing to swap.
root = [][]
Single node
Swapping two nulls changes nothing.
root = [1][1]
One child
The left child moves to the right.
root = [2, 1][2, null, 1]
← Maximum Depth of Binary TreeSame Tree →