Problem overview
The method invertTree receives the root of a binary tree, mirrors the tree from left to right, and returns its root. At every node, the left child and the right child trade places, all the way down to the leaves. The lesson provides the TreeNode class, where each node has val, left and right, and a missing child is None.
Trees are written in level order, top to bottom and left to right. For [4, 2, 7, 1, 3, 6, 9] the root 4 has children 2 and 7. Inverting swaps them, then swaps 1 and 3 under 2, and 6 and 9 under 7. The result is [4, 7, 2, 9, 6, 3, 1]. For [1, 2, None, 3], a line of nodes going left, every left child becomes a right child and the result is [1, None, 2, None, 3]. An empty tree is its own mirror.
Approach: swap, then mirror each side
A mirror image swaps left and right at every node, not only at the root. Swapping just the root's two children would put the subtrees on opposite sides, but each subtree would still face the old way.
That description is recursive: swap the two children of a node, then mirror the subtree under each child in the same way. The base case is an empty tree, which has nothing to swap. Each node is handled once, so the running time is O(n) for n nodes, which is the problem's follow-up.
The recursion changes the tree in place. It relinks the existing nodes and creates none, so the root that comes in is the root that goes out.
For [1, 2, 3] the steps are: swap 2 and 3 under 1, giving 3 on the left and 2 on the right. Then mirror the subtree at 3 and the subtree at 2. Both are single nodes with two empty children, so swapping changes nothing. The result is [1, 3, 2].
Step by step
- Handle the empty tree. If
not rootis true, returnNone. This also ends the recursion when it steps past a leaf. - Swap the children in one assignment: the two targets
root.left, root.rightgo on the left of the=, and the two values in the opposite order,root.right, root.left, go on the right. Python evaluates the whole right side first, so neither child is lost. - Mirror the left subtree. After the swap, call
self.invertTree(root.left). The call swaps children all the way down that subtree, so the node it returns doesn't need to be kept. - Mirror the right subtree with
self.invertTree(root.right). - Return
root. It is still the top of the tree, which is now mirrored.
The solution in Python
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
Python details worth a closer look:
- Tuple assignment as a swap.
a, b = b, abuilds the pair of values on the right first and then assigns them. No temporary variable is needed. Written as two separate lines,root.left = root.rightfollowed byroot.right = root.left, the second line would copy the already overwritten value: both children would end up as the original right child, and the original left subtree would be lost. - Attributes work as swap targets. The targets can be any assignable names, including
root.leftandroot.right. - Return values of the recursive calls are ignored. Both calls change the tree in place, and the nodes they return are the same nodes already linked into it.
- Same object back. The function returns the object it received. For a tree built as
[1, 2, 3], the returned node is the input root, and afterwards its left child holds 3 and its right child holds 2. - The recursion limit. Python's default of about 1,000 nested calls is far above the 400 levels the constraints allow.
Complexity
Time: O(n). Every node is visited once and does a constant amount of work: a check and a swap. The calls made on missing children return at once.
Space: O(h), where h is the height of the tree. The call stack holds one frame per level of the path being explored: about log n for a balanced tree and n for a chain of nodes. No new nodes are created.
Edge cases and common mistakes
- Empty tree.
[]returnsNone. Without the base case,root.leftonNonewould raiseAttributeError. - Single node.
[1]stays[1]: both children areNone, and swapping them changes nothing. - A chain.
[1, 2, None, 3]becomes[1, None, 2, None, 3]: the left-going line is now a right-going line. - Swapping only at the root. Each subtree must be mirrored too, which is what the two recursive calls do.
- Losing a child in the swap. Assigning the two children in two separate statements without a temporary variable overwrites one of them. The tuple assignment avoids that.
- Recursing before swapping, or after. Either order is correct, as long as each node's children are swapped once. The recursive calls in the solution use
root.leftandroot.rightafter the swap, so each call goes into the subtree that is now on that side. Both subtrees still get visited. - Swapping twice. Swapping a node's children before the recursion and again after it would put them back where they started.
Testing
[4, 2, 7, 1, 3, 6, 9]gives[4, 7, 2, 9, 6, 3, 1].[1, 2, None, 3]gives[1, None, 2, None, 3].[]gives an empty tree.[1]gives[1].[1, 2, 3]gives[1, 3, 2].
