Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in JavaScript: O(n) Recursion with a Swap

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 5
    Ctrl + Enter to check

    JAVASCRIPT · BINARY TREES

    Invert Binary Tree in JavaScript, explained

    Problem overview

    invertTree(root) receives the root of a binary tree and returns the root of the same tree, mirrored from left to right. At every node, the left and right children trade places, all the way down to the leaves.

    The lesson provides the TreeNode constructor: each node has a val, and its left and right start as null. The tree is changed in place, so the function returns the same root it received.

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

    Approach: swap, then repeat below

    A mirror image swaps left and right at every node. If you swap the two children of a node and then mirror each of those two subtrees, the whole tree below the node is mirrored. The subtrees are smaller trees of the same kind, so this is a recursion with the base case "an empty tree has nothing to swap".

    The follow-up asks for O(n) time, visiting each node once. The recursion does that: each node is reached by one call from its parent, and swapping its two child references is constant work.

    The order of the two actions doesn't affect the result. Swapping first and then recursing, or recursing first and then swapping, both mirror every node exactly once. The lesson swaps first, so the recursive calls are made on the children in their new positions.

    Step by step

    1. Write the base case. If root is null, written as !root, return null. This ends the recursion when a call steps past a leaf.
    2. Swap the children in one line with a destructuring assignment. The array on the right of the = is built first, from the old children, so neither child is lost.
    3. Mirror the left subtree by calling this.invertTree on root.left, the subtree that is on the left after the swap. The call changes that subtree in place, so the node it returns doesn't need to be kept.
    4. Mirror the right subtree the same way.
    5. Return root. It is still the top of the tree, which is now mirrored.

    The solution in JavaScript

    class Solution {
        invertTree(root) {
            if (!root) {
                return null;
            }
            [root.left, root.right] = [root.right, root.left];
            this.invertTree(root.left);
            this.invertTree(root.right);
            return root;
        }
    }
    

    The JavaScript details worth a closer look:

    • Destructuring swap. [a, b] = [b, a] first builds a new array holding the current values of b and a, then assigns its elements to a and b. With x = 1 and y = 2, [x, y] = [y, x] leaves x as 2 and y as 1, with no temporary variable. Here the targets are the properties root.left and root.right, which works the same way.
    • The semicolon before the swap matters. A statement that starts with [ can be read as a continuation of the line above it, as an index into its value. The line before the swap ends in a semicolon, which keeps the two statements apart. If you leave semicolons out of your own code, put one at the start of such a line.
    • Nodes are references. The swap exchanges which node each field points to. No node is copied or moved in memory, so the subtrees keep their identity: a node that was root.left before the call is root.right after it.
    • The return values of the recursive calls are ignored. Each call returns the node it was given, which is already in place, so there is nothing to assign.
    • this.invertTree. A recursive call to a method of the same class needs the this. prefix.

    Complexity

    Time: O(n). The function is called once for each node and once for each missing child, at most 2n + 1 calls, with constant work in each.

    Space: O(h), where h is the height of the tree, for the recursion stack. It is about log n for a balanced tree and n for a chain. The statement limits the height to 400 levels. No new nodes are created.

    Edge cases and common mistakes

    • Empty tree. invertTree(null) returns null before any field is read.
    • A single node. The tree [5] stays [5]: swapping two null children changes nothing.
    • Nodes with one child. [1, null, 2] becomes [1, 2]: the right child moves to the left. The swap works even when one side is null.
    • Swapping with two separate assignments. root.left = root.right; root.right = root.left; loses the old left child, because the second line copies the value that was just written. Use a temporary variable or the destructuring swap.
    • Swapping only at the root. Exchanging the root's children without recursing mirrors only the top level. Each subtree keeps its old orientation.
    • Forgetting the base case. The recursion would reach a null child and fail when it reads root.left of null.
    • Expecting a copy. The tree is changed in place. After the call, the original variable holding the root sees the mirrored tree.

    Testing

    Level-order results, with null for a missing child and trailing nulls left out:

    • [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 [].
    • [5] gives [5].
    • [1, 2, 3] gives [1, 3, 2].
    • [1, null, 2] gives [1, 2].
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free