Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in Scala: Swapping Children Recursively 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

    SCALA · BINARY TREES

    Invert Binary Tree in Scala, explained

    Problem overview

    invertTree receives the root of a binary tree, mirrors it 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 node class. A TreeNode is created with a value, TreeNode(4), and has two fields, left and right, which hold the children or null. The lesson's tests print a tree in level order with spaces between the values, using -1 for a missing child and leaving out trailing ones.

    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,null,3], a line going left, becomes [1,null,2,null,3], a line going right. An empty tree is its own mirror. The follow-up asks for O(n) time, visiting each node once.

    Approach: swap at one node, then trust the recursion

    Think about a single node. To mirror the tree under it, swap its two children, then mirror the subtree under each child. Both subtrees are smaller trees of the same kind, so the same method does the job, and the recursion works its way down to the leaves.

    The base case is an empty tree, null. It has nothing to swap, and it is where the recursion stops after stepping past a leaf.

    The order of the swap and the two recursive calls does not matter for the result. Mirroring the children first and swapping afterwards produces the same tree. The lesson swaps first, so after the swap the two recursive calls handle the subtree that is now on the left and the one that is now on the right.

    The method changes the tree in place and returns the same root node it received. No new nodes are created.

    Step by step

    1. Base case. If root == null, return null.
    2. Save the left child. val temp = root.left keeps the old left child. The next line overwrites root.left, and without temp that subtree would be lost.
    3. Finish the swap. root.left becomes root.right, and root.right becomes temp. The two children have traded places.
    4. Mirror the left subtree. Call invertTree(root.left). The call swaps children all the way down that subtree, in place, so the returned node isn't needed.
    5. Mirror the right subtree with invertTree(root.right). Afterwards every node below root has had its children swapped.
    6. Return root. It is still the top of the tree, which is now mirrored.

    The solution in Scala

    class Solution {
        def 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
        }
    }
    

    The Scala details worth a closer look:

    • Fields are assignable. root.left = root.right works because the lesson declares left and right as vars. A val field could not be reassigned.
    • Parameters are not variables. root itself cannot be reassigned, but the object it refers to can change. The method relies on that: it modifies the node's fields, not the parameter.
    • The result of a recursive call is ignored. invertTree(root.left) returns a TreeNode that the code throws away. This is legal as a statement. It is safe here because the call returns the same node it was given, already mirrored in place.
    • Return type. A recursive method needs its result type spelled out, as : TreeNode here. Both return null and return root fit it, because null is a valid TreeNode value for this class.
    • val temp. The temporary is assigned once, so it is a val.

    Complexity

    Time: O(n). The method is called once for each node, and once for each missing child, which adds at most n + 1 calls. Each call does a constant amount of work apart from the recursive calls.

    Space: O(h), where h is the height of the tree, for the stack of active calls. A balanced tree uses about log n frames, and a line of n nodes uses n. The lesson promises at most 400 levels.

    Edge cases and common mistakes

    • An empty tree. invertTree(null) returns null, which the tests print as -1.
    • A single node. Both children are null, the swap changes nothing, and the tree prints as it was: 7 stays 7.
    • A line of nodes. [1,2,null,3] prints as 1 2 -1 3 before the call and 1 -1 2 -1 3 after it.
    • Swapping without temp. Writing root.left = root.right followed by root.right = root.left sets both children to the old right child. For a root with children 2 and 3, both end up as 3, and the 2 is lost.
    • Skipping the recursive calls. Only the root's two children would swap, and everything below them would keep its old orientation.
    • Inverting twice. The second call restores the original tree. Inverting [2,1,3] twice prints 2 1 3.
    • Expecting a new tree. The original tree is changed. After the call, the variable that held the old root sees the mirrored tree, and the returned node is that same node.

    Testing

    • [4,2,7,1,3,6,9] prints 4 2 7 1 3 6 9 before the call and 4 7 2 9 6 3 1 after it.
    • [1,2,null,3] becomes 1 -1 2 -1 3.
    • [1,2,3] becomes 1 3 2, and the returned node is the same object as the root passed in.
    • [7] stays 7.
    • An empty tree returns null.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free