Start learning free

LESSON 206 OF 321 · BINARY TREES

Invert Binary Tree in Java: 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 null.

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,null,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,null,4,7]
Output: [6,9,2,null,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,null,5,null,3]
Output: [8,5,null,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 6
    Ctrl + Enter to check

    JAVA · BINARY TREES

    Invert Binary Tree in Java, explained

    Problem overview

    The method invertTree receives the root of a binary tree, mirrors the tree from left to right, and returns the root. Mirroring means that 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, with an int val, a TreeNode left, a TreeNode right and a constructor TreeNode(int x). A missing child is null.

    The tree [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1]: 2 and 7 swap under the root, 1 and 3 swap under 2, and 6 and 9 swap under 7. The tree [1,2,null,3], a line going down to the left, becomes [1,null,2,null,3], a line going down to the right. An empty tree is its own mirror.

    Approach: swap, then recurse

    A tree mirrored from left to right is a root whose two subtrees have traded places and have each been mirrored themselves. That is already a recursive definition:

    1. Swap the node's two children.
    2. Mirror the subtree that is now on the left.
    3. Mirror the subtree that is now on the right.

    Because the swap is done on the existing nodes, the tree is changed in place: no new nodes are created, and the root you were given is still the root of the result. Every node is visited once, so the time is O(n).

    The order of the three actions is flexible. Swapping first and then recursing, as here, visits each node on the way down. Recursing into both children first and swapping afterwards would give the same mirrored tree. What matters is that every node gets its swap exactly once. The same idea also works without recursion: keep nodes in a queue or a stack, and swap the children of each node you take out.

    Step by step

    1. Base case. If root == null, return null. An empty tree has nothing to swap, and this check also stops the recursion below the leaves.
    2. Save the left child. Store root.left in a TreeNode named temp. The next line overwrites root.left, so without temp the old left child would be lost.
    3. Finish the swap. Set root.left = root.right and then root.right = temp. The children have traded places.
    4. Mirror the left subtree by calling invertTree(root.left). The call swaps the children all the way down that subtree in place, so the value it returns doesn't need to be kept.
    5. Mirror the right subtree the same way with invertTree(root.right).
    6. Return root. It is still the top of the tree, and the tree below it is now mirrored.

    The solution in Java

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if (root == null) {
                return null;
            }
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            invertTree(root.left);
            invertTree(root.right);
            return root;
        }
    }
    

    Java details worth knowing:

    • The swap needs a temporary variable. Writing root.left = root.right; root.right = root.left; would make both children the old right child, because the first line has already replaced the left one. Java has no tuple assignment to swap two values at once.
    • Assigning swaps references, not nodes. root.left = root.right makes the field refer to the same node object as root.right. No subtree is copied. The swap is one step, whatever the size of the subtrees.
    • Objects are passed by reference value. The method receives a copy of the reference, but it points to the caller's node, so changing root.left and root.right changes the caller's tree. That is why the returned value of the recursive calls can be ignored. Reassigning the parameter root itself would not affect the caller.
    • Checking for null comes first, because root.left on a null reference throws a NullPointerException.

    Complexity

    Time: O(n). Each node is visited once and each visit does a swap, a constant amount of work. The null children add at most n + 1 calls that return at once.

    Space: O(h) for the call stack, where h is the height of the tree. That is about log n for a balanced tree and n for a chain; here the tree is at most 400 levels deep.

    Edge cases and common mistakes

    • Empty tree. root = null returns null. The lesson's tests print an empty tree as -1.
    • A single node. It has no children to swap and comes back unchanged.
    • A node with only one child. The swap still works: the missing child is null, so the existing child moves to the other side. [1,2,null,3] gives [1,null,2,null,3].
    • Swapping only the root. Without the recursive calls, only the top two children trade places and the subtrees below keep their old orientation.
    • Losing a subtree in the swap. Without temp, one of the two children is overwritten and its whole subtree disappears from the tree.
    • Returning the wrong node. The method returns root, the same node it received, because inverting rearranges the children and not the top.

    Testing

    These results come from running the solution on trees written in level order:

    • [4,2,7,1,3,6,9] gives [4,7,2,9,6,3,1].
    • [1,2,null,3] gives [1,null,2,null,3].
    • [] gives an empty tree.
    • [2,1,3] gives [2,3,1].
    • For [1,2], the returned node is the same object as the root passed in.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free