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:
- swap its two children;
- mirror the subtree that is now on the left;
- 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
- Match on
root. The whole body is amatch, with no semicolon after its closing brace, so its value is what the function returns. - The base case.
None => None: an empty tree gives an empty tree. - The node arm.
Some(mut node)binds the box asnode. Themutin the pattern makes the variable mutable, likelet mut, because the children are about to change. - 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. - Mirror the left subtree.
node.left.take()moves the subtree out and leavesNonein its place. The recursive call owns what it receives and returns it mirrored, and the result is stored back innode.left. - Mirror the right subtree the same way with
node.right. - 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. Writingnode.left = node.right;would move the right child out ofnodeand drop the old left child. The compiler then rejects any later use ofnode, such asSome(node), with the erroruse of partially moved value: `node`.swapexchanges the two values through two mutable references, so both fields stay filled at all times and nothing is lost. - The two
&mutborrows. Borrowingnode.leftandnode.rightmutably at the same time is allowed, because they are different fields of the same box. - Why
take().Option::takereplaces the value withNoneand returns the old one. It moves the subtree out of a field that is only reachable throughnode. 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 theNonewas left. - Assignment and the right-hand side.
node.left = Self::invert_tree(node.left.take());first evaluates the right side, which emptiesnode.leftand 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 ofroot.mutbelongs to the new variablenode, not to the function's parameter, which is why the signature has nomut.- 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-1in the lesson's tests. - A single node.
[5]stays[5]: both children areNone, 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 as4 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 matchOption<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 as4 7 2 9 6 3 1.[1, 2, None, 3]gives[1, None, 2, None, 3], printed as1 -1 2 -1 3.[]gives[], printed as-1.[5]gives[5].
