Problem overview
The method invertTree receives the root of a binary tree, mirrors the tree 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 TreeNode class, with an int val, a TreeNode left, a TreeNode right and a constructor TreeNode(int x). A missing child is null.
The tree [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1]: 2 and 7 swap under the root, 1 and 3 swap under 2, and 6 and 9 swap under 7. The tree [1,2,null,3], a line going down to the left, becomes [1,null,2,null,3], a line going down to the right. An empty tree is its own mirror.
Approach: swap, then recurse
A tree mirrored from left to right is a root whose two subtrees have traded places and have each been mirrored themselves. That is already a recursive definition:
- Swap the node's two children.
- Mirror the subtree that is now on the left.
- Mirror the subtree that is now on the right.
Because the swap is done on the existing nodes, the tree is changed in place: no new nodes are created, and the root you were given is still the root of the result. Every node is visited once, so the time is O(n).
The order of the three actions is flexible. Swapping first and then recursing, as here, visits each node on the way down. Recursing into both children first and swapping afterwards would give the same mirrored tree. What matters is that every node gets its swap exactly once. The same idea also works without recursion: keep nodes in a queue or a stack, and swap the children of each node you take out.
Step by step
- Base case. If
root == null, returnnull. An empty tree has nothing to swap, and this check also stops the recursion below the leaves. - Save the left child. Store
root.leftin aTreeNodenamedtemp. The next line overwritesroot.left, so withouttempthe old left child would be lost. - Finish the swap. Set
root.left = root.rightand thenroot.right = temp. The children have traded places. - Mirror the left subtree by calling
invertTree(root.left). The call swaps the children all the way down that subtree in place, so the value it returns doesn't need to be kept. - Mirror the right subtree the same way with
invertTree(root.right). - Return
root. It is still the top of the tree, and the tree below it is now mirrored.
The solution in Java
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
Java details worth knowing:
- The swap needs a temporary variable. Writing
root.left = root.right; root.right = root.left;would make both children the old right child, because the first line has already replaced the left one. Java has no tuple assignment to swap two values at once. - Assigning swaps references, not nodes.
root.left = root.rightmakes the field refer to the same node object asroot.right. No subtree is copied. The swap is one step, whatever the size of the subtrees. - Objects are passed by reference value. The method receives a copy of the reference, but it points to the caller's node, so changing
root.leftandroot.rightchanges the caller's tree. That is why the returned value of the recursive calls can be ignored. Reassigning the parameterrootitself would not affect the caller. - Checking for
nullcomes first, becauseroot.lefton anullreference throws aNullPointerException.
Complexity
Time: O(n). Each node is visited once and each visit does a swap, a constant amount of work. The null children add at most n + 1 calls that return at once.
Space: O(h) for the call stack, where h is the height of the tree. That is about log n for a balanced tree and n for a chain; here the tree is at most 400 levels deep.
Edge cases and common mistakes
- Empty tree.
root = nullreturnsnull. The lesson's tests print an empty tree as-1. - A single node. It has no children to swap and comes back unchanged.
- A node with only one child. The swap still works: the missing child is
null, so the existing child moves to the other side.[1,2,null,3]gives[1,null,2,null,3]. - Swapping only the root. Without the recursive calls, only the top two children trade places and the subtrees below keep their old orientation.
- Losing a subtree in the swap. Without
temp, one of the two children is overwritten and its whole subtree disappears from the tree. - Returning the wrong node. The method returns
root, the same node it received, because inverting rearranges the children and not the top.
Testing
These results come from running the solution on trees written in level order:
[4,2,7,1,3,6,9]gives[4,7,2,9,6,3,1].[1,2,null,3]gives[1,null,2,null,3].[]gives an empty tree.[2,1,3]gives[2,3,1].- For
[1,2], the returned node is the same object as therootpassed in.
