Problem overview
The function 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 node type in a comment above the class: a TreeNode struct with an int val, two pointers left and right, and one constructor taking the value, which sets both pointers to null.
The tree [4,2,7,1,3,6,9] (level order) has root 4 with children 2 and 7. Node 2 has children 1 and 3, and node 7 has children 6 and 9. After inverting, 7 is on the left and 2 on the right, 7 has children 9 and 6, and 2 has children 3 and 1. In level order the result is [4,7,2,9,6,3,1].
A line of nodes going left, [1,2,NULL,3], becomes a line going right, [1,NULL,2,NULL,3]. An empty tree is its own mirror.
The follow-up asks for O(n) time, visiting each of the n nodes once.
Approach: swap, then mirror both subtrees
A mirror image of a tree is the same operation at every level. Mirroring a tree means:
- swap the root's two children;
- mirror the subtree that is now on the left;
- mirror the subtree that is now on the right.
Each subtree is a smaller binary tree, so steps 2 and 3 are the same problem, and recursion handles them. The base case is the empty tree: a null pointer has nothing to swap, so the function returns it as it is. That check also ends the recursion below every leaf.
The work happens in place. The nodes stay where they are in memory, and only their left and right pointers are exchanged. No new nodes are created, which is why the function can return the same root it received.
The order of the swap and the two recursive calls doesn't matter for the result. Swapping first, as the lesson does, means the calls then mirror root->left and root->right as they stand after the swap. Calling first and swapping afterwards produces the same tree, because each subtree gets mirrored once either way.
Step by step
- Handle the empty tree. If
rootis null (!root), returnnullptr. This is also the stop condition when the recursion steps past a leaf. - Swap the children.
swap(root->left, root->right)exchanges the two pointers. This line is the mirror itself. - Mirror the left subtree by calling
invertTree(root->left). The call changes that subtree in place, so there is no need to store what it returns. - Mirror the right subtree with
invertTree(root->right). After both calls, every node below the root has had its children swapped as well. - Return
root. It is still the top of the tree, which is now mirrored.
The solution in C++
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (!root) {
return nullptr;
}
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
The C++ details worth a closer look:
swapon pointers.swap(a, b)from the standard library exchanges the values of its two arguments. Here the arguments are the pointer fieldsroot->leftandroot->right, so the two subtrees change sides without copying any node.- Ignoring the return value is fine.
invertTree(root->left);is a call as a statement. The nodes are changed through the pointers, androot->leftalready points at the right place after the swap. - The input is modified. The original tree no longer exists afterwards. Any other pointer to a node of that tree now sees the mirrored children. To keep the original, build a new tree with
new TreeNode(root->val)and set its children to the inverted subtrees of the opposite sides. - Null before arrow.
root->lefton a null pointer is undefined behaviour, so the null check must come before the swap. After it, the children can be null, and the recursive calls handle that through the same check. - Stack depth. The recursion is as deep as the tree, at most 400 levels here, which the stack handles easily.
Complexity
Let n be the number of nodes and h the height.
Time: O(n). Each node is visited once and does one swap. Each null child adds one call that returns immediately, and a tree with n nodes has n + 1 null children, so there are 2n + 1 calls in all.
Space: O(h). The only extra memory is the call stack, one frame per level on the current path: O(log n) for a balanced tree and O(n) for a chain.
Edge cases and common mistakes
- Empty tree. A null root returns
nullptr, an empty tree again. - Single node. The swap exchanges two null pointers, the calls return at once, and the same node is returned.
- Missing children.
[1,2,NULL,3]becomes[1,NULL,2,NULL,3]: swapping a child with a null pointer is fine, and it moves the child to the other side. - Only swapping at the root. Swapping the top two children without recursing gives
[4,7,2,6,9,1,3]for the first example, with the lower levels unmirrored. - Swapping twice per node. A second swap would undo the first. Inverting a tree twice returns the original, which is a handy check but not what one call should do.
- Swapping values instead of pointers. Exchanging
valfields moves the data but leaves the shape alone, so the tree is not mirrored.
Testing
[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[].[5]gives[5].[1,2,3,NULL,4]gives[1,3,2,NULL,NULL,4].- Inverting
[4,2,7,1,3,6,9]twice gives back[4,2,7,1,3,6,9].
