Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in Kotlin: 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

    KOTLIN · BINARY TREES

    Invert Binary Tree in Kotlin, explained

    Problem overview

    invertTree receives the root of a binary tree, a TreeNode?, 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 node class: a TreeNode has an Int field value and two nullable children, left and right.

    The tree [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1]. First 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

    Mirroring a tree means swapping the two children of the root and then mirroring each of those subtrees. Each subtree is a binary tree, so the same function can do it. That is a recursive solution with the empty tree as the base case.

    The function changes the tree in place: it does not build a new one. It visits every node once, so the time is O(n) for n nodes.

    Step by step

    1. Handle the empty tree. If root == null, return null. This also stops the recursion when it steps past a leaf.
    2. Save the left child in a val named temp. The next line overwrites root.left, and temp keeps the old left child so it isn't lost.
    3. Finish the swap. Set root.left to root.right, and root.right to temp. The two 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 node it returns is not needed.
    5. Mirror the right subtree the same way.
    6. Return root. It is still the top of the tree, which is now mirrored.

    The solution in Kotlin

    class Solution {
        fun invertTree(root: TreeNode?): TreeNode? {
            if (root == null) {
                return null
            }
            val temp = root.left
            root.left = root.right
            root.right = temp
            invertTree(root.left)
            invertTree(root.right)
            return root
        }
    }
    

    Some Kotlin details in this code:

    • After the if (root == null) check that returns, Kotlin knows root is not null (a smart cast), so root.left and root.right need no ?..
    • The children have the type TreeNode?, so temp has that type too, and assigning it back to root.right is allowed.
    • Calling invertTree(root.left) as a statement and ignoring its return value is fine in Kotlin. The function's work is the swapping it does along the way.
    • The tree is changed where it stands. The returned node is the same object as the argument: for [1,2,null,3], invertTree(t) === t is true.

    Following the first example

    Printing the tree in level order before and after the call:

    4,2,7,1,3,6,9
    4,7,2,9,6,3,1
    

    The root 4 swaps its children, so 7 is now on the left and 2 on the right. The recursion then swaps the children of 7 (6 and 9 become 9 and 6) and of 2 (1 and 3 become 3 and 1).

    Complexity

    Time: O(n). Every node is visited once, and each visit does a constant amount of work: one swap and two calls.

    Space: O(h), where h is the height of the tree. The recursion keeps one call open per level of the current path: about log n for a balanced tree and n for a chain. The lesson's trees are at most 400 levels deep.

    Edge cases and common mistakes

    • Empty tree. null comes back as null.
    • A single node. Both children are null, so swapping changes nothing.
    • Only one child. A node with a left child and no right child ends up with a right child and no left one. In [5,1] the 1 moves to the right side.
    • Losing a subtree. Writing root.left = root.right and then root.right = root.left without temp makes both children the same node, and the original left subtree is gone.
    • Skipping the recursion. Swapping only the root's children gives a tree whose lower levels are not mirrored. Every node needs its own swap.

    Testing

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