Skip to content

Invert Binary Tree

Mirror a binary tree by swapping the left and right child of every node.

EasyTree DFS and BST
Solve on LeetCode

The problem

You get the root of a binary tree. Turn it into its mirror image, so that the left and right children of every node trade places, and return the root. An empty tree stays empty.

Input root = [8, 3, 10, 1, 6, null, 14]

Output [8, 10, 3, 14, null, 6, 1]

10 and 3 swap under the root, 1 and 6 swap under 3, and 14 moves from the right of 10 to its left.

Input root = [5, 9]

Output [5, null, 9]

The only child, 9, moves from the left side to the right side.

How to spot the pattern

  • The same small change, swapping two children, has to happen at every node.
  • Each subtree can be fixed on its own, without knowing anything about the rest of the tree.

The idea

The mirror of a tree is its root with the mirrored right subtree on the left and the mirrored left subtree on the right. So mirror both subtrees with the same function, then hang them on the opposite sides. Any visiting order works, as long as every node gets its children swapped exactly once.

Brute force: Build a separate mirrored copy of the tree, which is also O(n) time but needs O(n) extra memory for the new nodes.

Step by step

  1. 1If the node is null, return null.
  2. 2Invert the left subtree and the right subtree recursively.
  3. 3Attach the inverted right subtree as the new left child and the inverted left subtree as the new right child.
  4. 4Return the node.

See the pattern move

The tree dfs and bst pattern on a small example. Step through it, or press play.

Code

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left = right   # the mirrored right side goes on the left
        root.right = left
        return root

Complexity

Time

O(n)

Space

O(h)

Each node is visited and swapped once; the recursion stack is as deep as the tree's height h.

Watch out for

  • Swapping without a temporary variable: after root.left = root.right, the old left subtree is lost.
  • Swapping only the root's children and forgetting to recurse into the subtrees.
  • Swapping node values instead of child links, which does not change the shape at all.

Follow-up questions

Can you do it without recursion?

Put the root in a queue; each time you take a node out, swap its two children and add the non-null ones to the queue. It is still O(n) time.

How would you check whether a tree is a mirror of itself?

Compare the left and right subtrees in mirror order: left.left with right.right and left.right with right.left, using the same recursion as Same Tree.

In Hinglish

Har node par left aur right bachche ki jagah badal do, aur dono subtrees mein yahi kaam recursion se karwa lo.

Related problems