Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in TypeScript: 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 5
    Ctrl + Enter to check

    TYPESCRIPT · BINARY TREES

    Invert Binary Tree in TypeScript, explained

    Problem overview

    The method invertTree 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 child and the right child trade places, all the way down to the leaves. The lesson provides the TreeNode class, with a val and two children, left and right, each a TreeNode or null.

    For the tree [4,2,7,1,3,6,9] the result is [4,7,2,9,6,3,1]. Under the root, 2 and 7 swap places, then 1 and 3 swap under 2, and 6 and 9 swap under 7. For [1,2,null,3], a line of nodes going left becomes a line going right: [1,null,2,null,3].

    Approach

    A mirror image swaps left and right at every node, and nothing else. So the work at one node is: swap its two children, then mirror each of the two subtrees the same way. Every subtree is a smaller tree of the same kind, which makes recursion a natural fit. An empty tree is its own mirror, which ends the recursion.

    The tree is changed in place: the same nodes are reused and only their left and right links change. Each node is visited once, so the time is O(n).

    Step by step

    1. Base case. If root is null (!root), return null. This also stops the recursion when it steps past a leaf.
    2. Swap the children. One destructuring assignment does it: the array [root.left, root.right] on the left of the = receives the array [root.right, root.left] on its right. The array on the right is built first, from the old children, so neither one is lost.
    3. Mirror the left subtree. Call this.invertTree(root.left). It swaps the children all the way down that subtree, in place, so the node it returns does not need to be kept.
    4. Mirror the right subtree. Call this.invertTree(root.right) the same way. After both calls, every node below the root has had its children swapped too.
    5. Return root. It is still the top of the tree, which is now mirrored.

    The solution in TypeScript

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

    Details for TypeScript:

    • The destructuring swap. [a, b] = [b, a] needs no temporary variable. The naive version fails: with root.left = root.right; root.right = root.left;, the first line overwrites the left child, so the second line copies the right child back onto itself. For a root with children 2 and 3, that leaves both children as 3, while the destructuring swap leaves 3 on the left and 2 on the right.
    • The assignment targets are properties. Destructuring can assign to root.left and root.right directly, not only to variables.
    • The order of swap and calls. Swapping first and recursing after, as here, mirrors the same subtrees as recursing first and swapping after. Either order gives the same tree, as long as each node's swap happens exactly once.
    • The return values of the recursive calls are ignored. The calls change the nodes themselves, so root.left and root.right already hold the mirrored subtrees.
    • Types. TreeNode | null is erased when the code compiles to JavaScript. At run time the only protection against an empty tree is the !root check.

    Complexity

    Time: O(n). Every node is visited once and does one swap. Space: O(h) for the call stack, where h is the height of the tree: about log n for a balanced tree and n for a chain. The lesson's trees are at most 400 levels deep, which is well within the call stack.

    Edge cases and common mistakes

    • Empty tree. root = [] arrives as null and the method returns null: nothing to swap.
    • A single node. Both children are null; swapping them changes nothing, and the node is returned as it is.
    • A missing child. Swapping a node with one child and one null moves the child to the other side. This is how [1,2,null,3] becomes [1,null,2,null,3].
    • Swapping only the root's children. That mirrors the top level but leaves the subtrees pointing the original way. The recursion is what carries the swap down.
    • Swapping the values instead of the links. Exchanging the val fields of the children would not move their subtrees.
    • Inverting twice. Applying invertTree twice gives back the original tree: [4,2,7,1,3,6,9] comes out unchanged.

    Testing

    The results below are written in level order, with null for a missing child and the trailing ones left out:

    TreeResult
    [4,2,7,1,3,6,9][4,7,2,9,6,3,1]
    [1,2,null,3][1,null,2,null,3]
    [][]
    [8][8]
    [1,2,3][1,3,2]
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free