Start learning free

LESSON 489 OF 673 · BINARY TREES

Invert Binary Tree in Python: Recursive Swap in O(n)

Practice O(n) Read the full explanation

You get the root of a binary tree. Turn it into its mirror image and return the root.

In the mirror image, every node's left and right children swap places. This is called inverting the tree.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as None.

The test results print a tree in the same order, with spaces between the values. A missing child prints as -1, and the -1s at the end are left out. For example, [6,9,2,None,7,4] prints as 6 9 2 -1 7 4. An empty tree prints as -1.

 

Example 1:

       6                     6
     /   \                 /   \
    2     9       →       9     2
     \   /                 \   /
      4 7                   7 4

Input: root = [6,2,9,None,4,7]
Output: [6,9,2,None,7,4]
Explanation: 2 and 9 swap places under the root.
4 moves from the right of 2 to its left.
7 moves from the left of 9 to its right.

Example 2:

  8                    8
   \                  /
    5       →        5
     \              /
      3            3

Input: root = [8,None,5,None,3]
Output: [8,5,None,3]
Explanation: Every right child becomes a left child.
The chain now goes down to the left.

Example 3:

Input: root = [7]
Output: [7]
Explanation: A single node has no children to swap.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from 0 to 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you mirror the tree in O(n) time for n nodes, touching each node just once?
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · BINARY TREES

    Invert Binary Tree in Python, explained

    Problem overview

    The method invertTree receives the root of a binary tree, mirrors the tree from left to right, and returns its root. At every node, the left child and the right child trade places, all the way down to the leaves. The lesson provides the TreeNode class, where each node has val, left and right, and a missing child is None.

    Trees are written in level order, top to bottom and left to right. For [4, 2, 7, 1, 3, 6, 9] the root 4 has children 2 and 7. Inverting swaps them, then swaps 1 and 3 under 2, and 6 and 9 under 7. The result is [4, 7, 2, 9, 6, 3, 1]. For [1, 2, None, 3], a line of nodes going left, every left child becomes a right child and the result is [1, None, 2, None, 3]. An empty tree is its own mirror.

    Approach: swap, then mirror each side

    A mirror image swaps left and right at every node, not only at the root. Swapping just the root's two children would put the subtrees on opposite sides, but each subtree would still face the old way.

    That description is recursive: swap the two children of a node, then mirror the subtree under each child in the same way. The base case is an empty tree, which has nothing to swap. Each node is handled once, so the running time is O(n) for n nodes, which is the problem's follow-up.

    The recursion changes the tree in place. It relinks the existing nodes and creates none, so the root that comes in is the root that goes out.

    For [1, 2, 3] the steps are: swap 2 and 3 under 1, giving 3 on the left and 2 on the right. Then mirror the subtree at 3 and the subtree at 2. Both are single nodes with two empty children, so swapping changes nothing. The result is [1, 3, 2].

    Step by step

    1. Handle the empty tree. If not root is true, return None. This also ends the recursion when it steps past a leaf.
    2. Swap the children in one assignment: the two targets root.left, root.right go on the left of the =, and the two values in the opposite order, root.right, root.left, go on the right. Python evaluates the whole right side first, so neither child is lost.
    3. Mirror the left subtree. After the swap, call self.invertTree(root.left). The call swaps children all the way down that subtree, so the node it returns doesn't need to be kept.
    4. Mirror the right subtree with self.invertTree(root.right).
    5. Return root. It is still the top of the tree, which is now mirrored.

    The solution in Python

    class Solution:
        def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
            if not root:
                return None
            root.left, root.right = root.right, root.left
            self.invertTree(root.left)
            self.invertTree(root.right)
            return root
    

    Python details worth a closer look:

    • Tuple assignment as a swap. a, b = b, a builds the pair of values on the right first and then assigns them. No temporary variable is needed. Written as two separate lines, root.left = root.right followed by root.right = root.left, the second line would copy the already overwritten value: both children would end up as the original right child, and the original left subtree would be lost.
    • Attributes work as swap targets. The targets can be any assignable names, including root.left and root.right.
    • Return values of the recursive calls are ignored. Both calls change the tree in place, and the nodes they return are the same nodes already linked into it.
    • Same object back. The function returns the object it received. For a tree built as [1, 2, 3], the returned node is the input root, and afterwards its left child holds 3 and its right child holds 2.
    • The recursion limit. Python's default of about 1,000 nested calls is far above the 400 levels the constraints allow.

    Complexity

    Time: O(n). Every node is visited once and does a constant amount of work: a check and a swap. The calls made on missing children return at once.

    Space: O(h), where h is the height of the tree. The call stack holds one frame per level of the path being explored: about log n for a balanced tree and n for a chain of nodes. No new nodes are created.

    Edge cases and common mistakes

    • Empty tree. [] returns None. Without the base case, root.left on None would raise AttributeError.
    • Single node. [1] stays [1]: both children are None, and swapping them changes nothing.
    • A chain. [1, 2, None, 3] becomes [1, None, 2, None, 3]: the left-going line is now a right-going line.
    • Swapping only at the root. Each subtree must be mirrored too, which is what the two recursive calls do.
    • Losing a child in the swap. Assigning the two children in two separate statements without a temporary variable overwrites one of them. The tuple assignment avoids that.
    • Recursing before swapping, or after. Either order is correct, as long as each node's children are swapped once. The recursive calls in the solution use root.left and root.right after the swap, so each call goes into the subtree that is now on that side. Both subtrees still get visited.
    • Swapping twice. Swapping a node's children before the recursion and again after it would put them back where they started.

    Testing

    • [4, 2, 7, 1, 3, 6, 9] gives [4, 7, 2, 9, 6, 3, 1].
    • [1, 2, None, 3] gives [1, None, 2, None, 3].
    • [] gives an empty tree.
    • [1] gives [1].
    • [1, 2, 3] gives [1, 3, 2].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free