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:
- If the tree is empty, there is nothing to do.
- Swap the node's two children.
- 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
- Handle the empty tree. Use
guard let node = root else { return nil }. This unwraps the optional into a constantnode, and theelseblock, which must leave the function, runs whenrootisnil. The same check stops the recursion when it steps past a leaf. - 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. - Mirror the left subtree. Call
invertTreeonnode.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. - Mirror the right subtree the same way, with
node.right. - 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.rightfollowed bynode.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.
nodeis declared withguard let, so it is a constant, yet assigning tonode.leftcompiles.TreeNodeis a class, a reference type, so the constant fixes which nodenoderefers to, not the node's contents. - Discarding the result with
_.invertTreereturns aTreeNode?. Calling it without using the value produces the warningresult of call to 'invertTree' is unused. Writing_ = invertTree(node.left)says that ignoring the value is intended. - Optionals everywhere.
node.leftandnode.rightare optionals, and so is the return type, so a missing child needs no special handling: it is passed to the recursive call, which returnsnilfor it. guardversusif let. After aguard 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.
nilgoes in andnilcomes 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].
