15% off all plans & roadmaps Use code

See plans

Invert Binary Tree

Updated

TL;DR: Invert a binary tree by swapping the left and right child of every node. A recursive preorder DFS does it in place in O(n) time and O(h) stack space.

Problem

Given the root of a binary tree, invert the tree and return its root. Inverting means every node's left and right children trade places, all the way down.

Example 1

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2

Input: root = [2,1,3]
Output: [2,3,1]

Example 3

Input: root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Constraints that matter

  • At most 100 nodes means any O(n) or even O(n^2) method passes, so the interview is about clean tree handling, not speed.
  • The node count can be 0, so the root can be null. Every approach must handle that before touching root.left.
  • Height is at most 100 in the worst case (a chain), so recursion depth is safe here. In production code with deep trees, prefer an explicit queue or stack.
  • Values are in [-100, 100] and never get compared or combined, so only the shape of the tree matters. Values ride along with their nodes.

View on LeetCode

Hints

Hint 1

This is a tree traversal problem.

Hint 2

Leave the input tree alone and construct a brand new tree.

Solution

Intuition

This is a tree traversal problem. The output depends on every node, so you must visit each one at least once. The open questions are what to do at each visit and in which order.

Picture a mobile hanging from a ceiling, where each bar holds two arms that can be flipped. You walk down from the top, flip each bar, and carry only your current path, which is the call stack.

Look at the definition of a mirror image. A tree is inverted when its root's two children trade places and each of those subtrees is itself inverted. That sentence is recursive, which points at a depth-first search. The same shape of problem appears in Same Tree, Symmetric Tree and Maximum Depth.

The work at one node is tiny: swap two pointers. You can do it before you recurse (preorder) or after (postorder). Both are correct, because swapping a node's children does not change what is inside each child's subtree. Preorder reads most naturally: swap here, then fix the children.

Why it works: after the swap at node x, the old right subtree hangs on the left and the old left subtree hangs on the right. Recursing on both subtrees inverts each one internally. By induction on height, the whole subtree under x is a mirror of the original.

Watch the pattern animation

Worked example

Input: root = [5, 3, 8, 2, null, 6, 10, null, null, null, null, 9]
Output: [5, 8, 3, 10, 6, null, 2, null, 9]
Explanation:
Node 5 has left child 3 and right child 8. Node 3 has only a left child 2. Node 8 has children 6 and 10, and node 10 has a left child 9.

After inversion, 5 has left child 8 and right child 3. Node 8 has left child 10 and right child 6, and 10 now holds 9 on its right. Node 3 holds 2 on its right.

Approach 1: Brute force: build a mirrored copy

Leave the input tree alone and construct a brand new tree. For each original node, allocate a new node with the same value. Hang the mirrored copy of the original right subtree on its left, and the mirrored copy of the original left subtree on its right.

Many people write this first because it follows the definition word for word and never mutates the input. It is correct, but it pays for a second tree.

Steps

  1. If root is null, return null.
  2. Create a new node with root.val.
  3. Set the new node's left to the mirrored copy of root.right.
  4. Set the new node's right to the mirrored copy of root.left.
  5. Return the new node.

Dry run

Run on the example [5,3,8,2,null,6,10,null,null,null,null,9].

  • copy(5) makes a new 5, then asks for copy(8) as its left and copy(3) as its right.
  • copy(8) makes a new 8 with left copy(10) and right copy(6).
  • copy(10) makes a new 10 with left copy(null) = null and right copy(9) = a new leaf 9.
  • copy(6) makes a leaf 6.
  • copy(3) makes a new 3 with left copy(null) = null and right copy(2) = a new leaf 2.

The returned tree is 5 with children 8 and 3, 8 with children 10 and 6, 10 with right child 9, and 3 with right child 2. Level order is [5,8,3,10,6,null,2,null,9], which matches the expected output. Seven new nodes were allocated.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of nodes. Each node triggers exactly one call that does constant work, and every null child triggers one extra constant-time call, so total calls are at most 2n + 1. The new tree holds n nodes, so memory is O(n) for the copy. The O(h) recursion stack is dominated by it.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        node = TreeNode(root.val)
        # the mirrored right side becomes the new left side, and vice versa
        node.left = self.invertTree(root.right)
        node.right = self.invertTree(root.left)
        return node

Approach 2: Iterative BFS with a queue

What's slow: the copy allocates n extra nodes, and the problem never asks for a new tree. It asks you to return the root of the inverted tree, so reusing the existing nodes is allowed and cheaper.

The insight that fixes it: a swap at one node does not depend on any other node. Visit every node in any order and swap its two child pointers where it stands. A queue gives a clean level-by-level visit order and needs no recursion.

Steps

  1. If root is null, return null.
  2. Put root in a queue.
  3. Pop a node from the front of the queue.
  4. Swap its left and right pointers.
  5. Push each non-null child onto the queue.
  6. Repeat until the queue is empty, then return root.

Dry run

Run on the example. Each row shows the node popped and the queue after its children are pushed.

PopAfter swapQueue after pushes
start[5]
5left 8, right 3[8, 3]
8left 10, right 6[3, 10, 6]
3left null, right 2[10, 6, 2]
10left null, right 9[6, 2, 9]
6leaf, no change[2, 9]
2leaf, no change[9]
9leaf, no change[]

The queue is empty, and the tree reads [5,8,3,10,6,null,2,null,9] in level order.

Complexity

TimeO(n)
SpaceO(w)

Let n be the node count and w the maximum number of nodes on one level. Each node enters the queue once and leaves once, and each pop does constant work, so time is O(n). The queue holds at most about two adjacent levels at any moment, so extra space is O(w). In the worst case, a full tree, that is O(n), since the last level holds about n/2 nodes.

PythonTested in our runner

from collections import deque
from typing import List, Optional

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        queue = deque([root])
        while queue:
            node = queue.popleft()
            node.left, node.right = node.right, node.left
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return root
Recursive Preorder Traversal pattern infographic for Invert Binary Tree

Solution pattern

Recursive Preorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 3: Recursive preorder DFS, swap in placeOptimalRecursive Preorder Traversal

What's slow: the queue can hold a whole level at once, which is about half the nodes in a full tree. You pay that memory only to control visit order, and visit order does not matter here.

The insight that fixes it: let the call stack do the bookkeeping. A depth-first walk keeps only the current root-to-node path, so extra space is the tree height h. At each node, swap the children first (preorder), then recurse into both. The function returns root, so the caller can reattach the subtree and the final return value is the original root.

Steps

  1. If root is null, return null. This is the base case.
  2. Swap root.left and root.right using a temp variable or tuple swap.
  3. Recurse on root.left, which is now the old right child.
  4. Recurse on root.right, which is now the old left child.
  5. Return root.

Dry run

Trace on the example. Depth is the recursion depth, and "children after swap" shows left, right.

StepCallDepthChildren after swapNext
1invert(5)08, 3go left to 8
2invert(8)110, 6go left to 10
3invert(10)2null, 9go left to null
4invert(null)3nonereturn null
5invert(9)3null, nullboth null, return 9
6back in 102donereturn 10
7invert(6)2null, nullreturn 6
8back in 81donereturn 8
9invert(3)1null, 2left null, then 2
10invert(2)2null, nullreturn 2
11back in 50donereturn 5

The final tree has 5 with children 8 and 3, 8 with children 10 and 6, 10 with right child 9, and 3 with right child 2. Level order is [5,8,3,10,6,null,2,null,9], the expected output. Maximum depth reached was 3, so the stack never held more than four frames.

Complexity

TimeO(n)
SpaceO(h)

Let n be the node count and h the tree height. Each node is entered once and does one swap, and each null child costs one constant-time call. That gives at most 2n + 1 calls, so time is O(n). The stack holds one frame per level on the current path, so space is O(h): about log n for a balanced tree and n for a chain. No new nodes are created.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        # preorder step: swap before descending
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

Common mistakes

  • Dereferencing before the null check, such as writing root.left first when root can be null. An empty tree is a valid input, so test if root is None: return None on the first line.
  • Writing root.left = invert(root.right) and then root.right = invert(root.left). The second line reads the left pointer you overwrote, so both sides end up with the same subtree. Save the old left in a temp variable, or use a tuple swap, and only then recurse.
  • Swapping only at the root. Doing root.left, root.right = root.right, root.left once and returning leaves every deeper subtree in its original orientation. Recurse into both children.
  • Forgetting return root at the end. The function signature promises the root back, and a missing return gives None or null to the caller, which looks like an empty answer.
  • Swapping node values instead of pointers. Exchanging left.val with right.val moves only the two children's values and leaves their subtrees where they were. Swap the child references.
  • In the BFS version, pushing children before the swap, or pushing null children. Null pushes crash on the next pop when you read node.left. Swap first, then push only non-null children.

Edge cases

  • Empty tree []: return null (or None) immediately, with no crash.
  • Single node [1]: the swap exchanges two nulls and the tree is unchanged.
  • Two nodes [1,2]: the left child 2 moves to the right, giving [1,null,2].
  • Left-leaning chain with 100 nodes: depth is 100, still safe for recursion, and it becomes a right-leaning chain.
  • Duplicate or negative values such as [-1,-1,-1]: values are never compared, so the result is the same shape with the same values.
  • Tree where only one side exists below a node, like node 10 in the example with only a left child 9: the child must end up on the right, and the null must move to the left.

Follow-ups interviewers ask

How would you do this without recursion?
Use an explicit queue for BFS or an explicit stack for DFS. Pop a node, swap its children, push the non-null children, and repeat until empty. Time stays O(n). The stack version uses O(h) extra space for a skewed tree walk and the queue version uses O(width). Neither can overflow the call stack.
What if the tree is far deeper than 100 levels and recursion might overflow?
Switch to the iterative version. A chain of a million nodes would blow the default recursion limit in Python and the call stack in most languages, while an explicit queue or stack lives on the heap. Both need O(n) space in the worst case, but only the iterative one is safe against stack overflow.
What if you must not modify the input tree?
Build a mirrored copy, which is the brute-force approach. Each call allocates a node with the same value and attaches the mirrored right copy on the left and the mirrored left copy on the right. It costs O(n) time and O(n) extra memory for the new nodes, and the original stays intact.

Invert Binary Tree FAQ

What is the time complexity of Invert Binary Tree?

O(n), where n is the number of nodes. Every node is visited once and the swap is constant work. No approach can beat this, because the output depends on every node.

Why use DFS for Invert Binary Tree?

The problem is recursive by definition: a tree is inverted when its children are swapped and both subtrees are inverted. A DFS follows that definition directly in about five lines and keeps only the current path in memory, so extra space is O(h). BFS works equally well but needs a queue.

Can Invert Binary Tree be solved in O(1) extra space?

Not with plain recursion or a queue. Recursion uses O(h) stack, and BFS uses O(width) queue space. Only a threaded traversal such as Morris traversal avoids that extra memory. It is much harder to write correctly, so interviews accept O(h) as the optimal answer here.

What is the space complexity of the recursive solution?

O(h), where h is the tree height, because the call stack holds one frame per level on the current path. For a balanced tree that is about log n. For a chain-shaped tree it is n. The tree itself is modified in place, so no extra nodes are allocated.

Does it matter whether I swap before or after the recursive calls?

No. Preorder (swap then recurse) and postorder (recurse then swap) give the same tree. Swapping a node's children does not alter what is inside either child's subtree, so the order of the two steps never changes the result. Keep the temp variable so you do not overwrite a pointer before reading it.

How do I write Invert Binary Tree in Python?

Return None for a null node, then run root.left, root.right = root.right, root.left, recurse on both children and return root. Python's tuple assignment evaluates the right side first, so the swap needs no temp variable. The recursion depth is at most 100 under the constraints, well under Python's default limit.

Asked at

See which companies ask this — Pro

Practise it