Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in Rust: Recursive Swap with take(), 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 None.

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,None,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,None,4,7]
Output: [6,9,2,None,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,None,5,None,3]
Output: [8,5,None,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 7
    Ctrl + Enter to check

    RUST · BINARY TREES

    Invert Binary Tree in Rust, explained

    Problem overview

    The function invert_tree receives the root of a binary tree, an Option<Box<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. The lesson provides TreeNode, whose left and right fields are each an Option<Box<TreeNode>>.

    Trees are written in level order, top to bottom and left to right, with None 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, None, 3], a line going left, becomes [1, None, 2, None, 3], a line going right. An empty tree is its own mirror.

    The lesson's tests print a tree in level order with spaces, -1 for a missing child, and the trailing missing children left out, so the first result prints as 4 7 2 9 6 3 1 and the empty tree as -1.

    Approach: swap, then mirror each child

    A mirrored tree is a tree whose children are swapped and whose children are themselves mirrored. That is a recursive definition, so the function does three things for a node:

    1. swap its two children;
    2. mirror the subtree that is now on the left;
    3. mirror the subtree that is now on the right.

    The base case is an empty tree, which stays empty. It also stops the recursion when it steps past a leaf. Each node is visited once, so the time is O(n) for n nodes.

    The function works in place: it reuses the nodes it is given, and no node is created. It takes ownership of the tree and hands the same nodes back, rearranged, as the returned tree.

    Step by step

    1. Match on root. The whole body is a match, with no semicolon after its closing brace, so its value is what the function returns.
    2. The base case. None => None: an empty tree gives an empty tree.
    3. The node arm. Some(mut node) binds the box as node. The mut in the pattern makes the variable mutable, like let mut, because the children are about to change.
    4. Swap the children with std::mem::swap(&mut node.left, &mut node.right). This exchanges the two values behind the references, without copying or dropping anything. It is the heart of the lesson.
    5. Mirror the left subtree. node.left.take() moves the subtree out and leaves None in its place. The recursive call owns what it receives and returns it mirrored, and the result is stored back in node.left.
    6. Mirror the right subtree the same way with node.right.
    7. Return the node. End the arm with Some(node), with no semicolon: the root of the mirrored tree.

    The solution in Rust

    impl Solution {
        fn invert_tree(root: Option<Box<TreeNode>>) -> Option<Box<TreeNode>> {
            match root {
                None => None,
                Some(mut node) => {
                    std::mem::swap(&mut node.left, &mut node.right);
                    node.left = Self::invert_tree(node.left.take());
                    node.right = Self::invert_tree(node.right.take());
                    Some(node)
                }
            }
        }
    }
    

    The Rust details worth a closer look:

    • Why std::mem::swap. Writing node.left = node.right; would move the right child out of node and drop the old left child. The compiler then rejects any later use of node, such as Some(node), with the error use of partially moved value: `node`. swap exchanges the two values through two mutable references, so both fields stay filled at all times and nothing is lost.
    • The two &mut borrows. Borrowing node.left and node.right mutably at the same time is allowed, because they are different fields of the same box.
    • Why take(). Option::take replaces the value with None and returns the old one. It moves the subtree out of a field that is only reachable through node. The recursive call takes its argument by value, so it owns the subtree and returns it mirrored. Assigning that result back to the field puts the mirrored subtree where the None was left.
    • Assignment and the right-hand side. node.left = Self::invert_tree(node.left.take()); first evaluates the right side, which empties node.left and mirrors the subtree, and then stores the result. The order is fixed, so there is no moment when the same subtree has two owners.
    • Some(mut node). The pattern moves the box out of root. mut belongs to the new variable node, not to the function's parameter, which is why the signature has no mut.
    • The Box. Box<TreeNode> is a pointer to a node on the heap, so a tree node can hold other tree nodes. Fields of the node are used through the box with no extra syntax. Moving the box moves only the pointer, not the subtree.

    Complexity

    Time: O(n). Each node gets one call, plus one call for each missing child, and each call does a constant amount of work: a swap, two take operations and a wrap in Some.

    Space: O(h), where h is the height of the tree, for the recursion stack. For a balanced tree this is about log n, and the lesson limits the depth to 400 levels, so a line-shaped tree is safe too.

    Edge cases and common mistakes

    • An empty tree. The first arm returns None, which prints as -1 in the lesson's tests.
    • A single node. [5] stays [5]: both children are None, so the swap changes nothing visible.
    • A node with one child. [1, 2, None, 3] becomes [1, None, 2, None, 3]: the swap moves the child from the left to the right at every level.
    • Dropping the recursion after the swap. Only the root's children trade places, and the subtrees below keep their old order. The tree [4, 2, 7, 1, 3, 6, 9] would come out as 4 7 2 6 9 1 3. The recursive calls are what carry the swap down to every node.
    • Forgetting to return the node. Ending an arm with a semicolon makes its value (), which doesn't match Option<Box<TreeNode>>, and the compiler reports an error.

    Testing

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