Problem overview
The method InvertTree 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 child and the right child trade places, all the way down to the leaves.
The lesson provides the TreeNode class: an int val and two TreeNode fields, left and right, which are null for a missing child. A node is created with new TreeNode(x).
The tree [4,2,7,1,3,6,9], listed level by level, becomes [4,7,2,9,6,3,1]. Under the root, 2 and 7 swap, then 1 and 3 swap under 2, and 6 and 9 swap under 7. For [1,2,null,3], a line of nodes going left becomes a line going right. An empty tree is its own mirror. The tests print a tree level by level with -1 for a missing child and trailing missing children left out, so the first result prints as 4 7 2 9 6 3 1.
Approach: swap, then mirror each side
A mirror image of a tree has the two subtrees of the root exchanged, and each of those subtrees is itself mirrored. So the method has three parts for a node: swap its two children, mirror the subtree that is now on the left, and mirror the subtree that is now on the right.
The recursion stops at an empty tree. A null node has nothing to swap and is returned as it is. Because every leaf has two null children, this base case is reached at the bottom of every path.
The tree is changed in place. No new nodes are made, and the method returns the same root it received, because the root is still at the top. Each node is visited once, so the time is O(n) for n nodes.
The order inside the method doesn't matter much. Swapping first and recursing after, as here, works, and so does recursing into both children first and swapping afterwards. What matters is that every node gets swapped exactly once.
Running the method on some trees prints these level-order results, before and after:
4 2 7 1 3 6 9 => 4 7 2 9 6 3 1
1 2 -1 3 => 1 -1 2 -1 3
-1 => -1
5 => 5
1 2 3 => 1 3 2
Step by step
- Write the base case. If
root == null, returnnull. An empty tree is its own mirror, and this check also stops the recursion after a leaf. - Swap the children in one line with a tuple assignment:
(root.left, root.right) = (root.right, root.left);. The right-hand tuple is built first from the old children, so neither is lost. - Mirror the left subtree by calling
InvertTree(root.left). It swaps the children all the way down that subtree in place, so the returned node doesn't need to be kept. - Mirror the right subtree with
InvertTree(root.right)in the same way. - Return
root, the top of the now mirrored tree.
The solution in C#
class Solution {
public TreeNode InvertTree(TreeNode root) {
if (root == null) {
return null;
}
(root.left, root.right) = (root.right, root.left);
InvertTree(root.left);
InvertTree(root.right);
return root;
}
}
The C# details worth knowing:
- Tuple assignment swaps without a temporary variable.
(a, b) = (b, a)evaluates the right side first and then assigns both targets. Witha = 1andb = 2it leavesaas 2 andbas 1. It works on fields such asroot.leftjust as well as on local variables. - Two plain assignments don't swap.
n.left = n.right; n.right = n.left;on a node with children 2 and 3 leaves both children as 3, because the first line overwrites the left child before the second line reads it. Without a tuple you need a temporary variable. - The returned values of the recursive calls are ignored. This is fine because the calls modify the nodes in place, and each child is still the same object after its call. The return value matters only for the top-level call.
- Nodes are references. The tree handed back is the same object graph as the one passed in: the returned root is the same object as the argument. Anyone else holding the old tree sees it mirrored too.
- Field names are lowercase. The provided
TreeNodehasval,leftandright. Use those exact names.
Complexity
Time: O(n). Each node is swapped once, and each missing child costs one call that returns at once.
Space: O(h), where h is the height of the tree, for the call stack. A balanced tree needs about log n frames, and a chain where every node has one child needs n. The lesson's trees are at most 400 levels deep.
Edge cases and common mistakes
- Empty tree. The method returns
null, which prints as-1. - A single node. Swapping two
nullchildren changes nothing, and the tree prints as5. - Missing children. A node with only a left child ends up with only a right child.
[1,2,null,3]becomes the level order1 -1 2 -1 3. - Swapping only at the root. Then just the top two subtrees trade places and the insides stay as they were. Every level has to be mirrored.
- Swapping twice. Mirroring a subtree and then swapping the children of the same node again undoes the work. Swap once per node.
- Swapping with two assignments. As shown above, that loses one child. Use the tuple or a temporary variable.
- Forgetting
return root. The tree is already mirrored in place, but the caller would get nothing back, and the code would not compile for a method with a return type.
Testing
These trees were run through the method and printed level by level with -1 for a missing child.
[4,2,7,1,3,6,9]gives4 7 2 9 6 3 1.[1,2,null,3]gives1 -1 2 -1 3.- An empty tree gives
-1. [5]gives5.[1,2,3]gives1 3 2.- For a chain of 10,000 left children, the root ends up with no left child and a right child.
