Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in Swift: O(n) Recursive 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 nil.

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,nil,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,nil,4,7]
Output: [6,9,2,nil,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,nil,5,nil,3]
Output: [8,5,nil,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

    SWIFT · BINARY TREES

    Invert Binary Tree in Swift, explained

    Problem overview

    The method invertTree(_ root: TreeNode?) -> TreeNode? 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 class: each node has a val and optional left and right children.

    The trees are written in level order, with nil for a missing child. The tree [4, 2, 7, 1, 3, 6, 9] becomes [4, 7, 2, 9, 6, 3, 1]: 2 and 7 trade places under the root, then 1 and 3 under 2, and 6 and 9 under 7. The tree [1, 2, nil, 3], a line going left, becomes [1, nil, 2, nil, 3], a line going right. An empty tree is its own mirror.

    The follow-up asks for O(n) time, visiting each of the n nodes once.

    Approach: swap the children, then mirror each subtree

    A mirror image swaps left and right everywhere, not just at the root. Swapping the two children of the root is only the first step: each child is the root of a smaller tree that must be mirrored too. This is recursion with a simple shape:

    1. If the tree is empty, there is nothing to do.
    2. Swap the node's two children.
    3. Mirror the subtree that is now on the left, and the one that is now on the right.

    The order of steps 2 and 3 doesn't change the result, as long as each node is swapped once. The version here swaps first and recurses afterwards. Every node is visited once, so the time is O(n).

    The recursion works in place. It changes the existing nodes and returns the same root it was given, so the returned tree shares all its nodes with the input.

    Step by step

    1. Handle the empty tree. Use guard let node = root else { return nil }. This unwraps the optional into a constant node, and the else block, which must leave the function, runs when root is nil. The same check stops the recursion when it steps past a leaf.
    2. Swap the children in one line with a tuple assignment: (node.left, node.right) = (node.right, node.left). Swift builds the tuple on the right from the old children first, so neither one is lost.
    3. Mirror the left subtree. Call invertTree on node.left, which is the old right child after the swap, and assign the result to _. The call swaps the children all the way down in place, so the returned node isn't needed.
    4. Mirror the right subtree the same way, with node.right.
    5. Return node. It is still the top of the tree, which is now mirrored.

    The solution in Swift

    class Solution {
        func invertTree(_ root: TreeNode?) -> TreeNode? {
            guard let node = root else {
                return nil
            }
            (node.left, node.right) = (node.right, node.left)
            _ = invertTree(node.left)
            _ = invertTree(node.right)
            return node
        }
    }
    

    The Swift details worth a closer look:

    • The tuple swap. A swap with two assignments, node.left = node.right followed by node.right = node.left, loses a child: the first line overwrites the left child, so the second line copies the right child back to where it already was. For the tree [1, 2, 3] that version returns [1, 3, 3]. With the tuple, the right-hand side is evaluated completely before the assignment happens, and the result is the correct [1, 3, 2].
    • A constant that can still change the tree. node is declared with guard let, so it is a constant, yet assigning to node.left compiles. TreeNode is a class, a reference type, so the constant fixes which node node refers to, not the node's contents.
    • Discarding the result with _. invertTree returns a TreeNode?. Calling it without using the value produces the warning result of call to 'invertTree' is unused. Writing _ = invertTree(node.left) says that ignoring the value is intended.
    • Optionals everywhere. node.left and node.right are optionals, and so is the return type, so a missing child needs no special handling: it is passed to the recursive call, which returns nil for it.
    • guard versus if let. After a guard let, the unwrapped constant stays available for the rest of the function without extra nesting, which suits a base case at the top.

    Complexity

    Time: O(n). The function runs once for each node and once for each missing child, and each call does a constant amount of work.

    Space: O(h) for the call stack, where h is the height of the tree. The statement limits the tree to 400 levels. No new nodes are created.

    Edge cases and common mistakes

    • Empty tree. nil goes in and nil comes out.
    • A single node. Both children are nil, so swapping them changes nothing, and the same node is returned.
    • Only one child. A missing child swaps like any other: [1, 2, nil, 3] becomes [1, nil, 2, nil, 3].
    • Swapping only at the root. Without the two recursive calls, [4, 2, 7, 1, 3, 6, 9] would come back with 7 and 2 swapped but their subtrees still unmirrored.
    • Swapping twice. If the code swapped a node's children both before and after the recursive calls, the tree would be restored to its original shape. Each node must be swapped exactly once.
    • Returning the wrong node. The function must return node, the root of the whole tree. Returning the result of the last recursive call would give the root of a subtree instead.

    Testing

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