Problem overview
invertTree(root) 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 constructor: each node has a val, and its left and right start as null. The tree is changed in place, so the function returns the same root it received.
Written in level order, the tree [4, 2, 7, 1, 3, 6, 9] becomes [4, 7, 2, 9, 6, 3, 1]: 2 and 7 swap under the root, then 1 and 3 under 2, and 6 and 9 under 7. The tree [1, 2, null, 3], a line going left, becomes [1, null, 2, null, 3], a line going right. An empty tree is its own mirror.
Approach: swap, then repeat below
A mirror image swaps left and right at every node. If you swap the two children of a node and then mirror each of those two subtrees, the whole tree below the node is mirrored. The subtrees are smaller trees of the same kind, so this is a recursion with the base case "an empty tree has nothing to swap".
The follow-up asks for O(n) time, visiting each node once. The recursion does that: each node is reached by one call from its parent, and swapping its two child references is constant work.
The order of the two actions doesn't affect the result. Swapping first and then recursing, or recursing first and then swapping, both mirror every node exactly once. The lesson swaps first, so the recursive calls are made on the children in their new positions.
Step by step
- Write the base case. If
rootisnull, written as!root, returnnull. This ends the recursion when a call steps past a leaf. - Swap the children in one line with a destructuring assignment. The array on the right of the
=is built first, from the old children, so neither child is lost. - Mirror the left subtree by calling
this.invertTreeonroot.left, the subtree that is on the left after the swap. The call changes that subtree in place, so the node it returns doesn't need to be kept. - Mirror the right subtree the same way.
- Return
root. It is still the top of the tree, which is now mirrored.
The solution in JavaScript
class Solution {
invertTree(root) {
if (!root) {
return null;
}
[root.left, root.right] = [root.right, root.left];
this.invertTree(root.left);
this.invertTree(root.right);
return root;
}
}
The JavaScript details worth a closer look:
- Destructuring swap.
[a, b] = [b, a]first builds a new array holding the current values ofbanda, then assigns its elements toaandb. Withx = 1andy = 2,[x, y] = [y, x]leavesxas 2 andyas 1, with no temporary variable. Here the targets are the propertiesroot.leftandroot.right, which works the same way. - The semicolon before the swap matters. A statement that starts with
[can be read as a continuation of the line above it, as an index into its value. The line before the swap ends in a semicolon, which keeps the two statements apart. If you leave semicolons out of your own code, put one at the start of such a line. - Nodes are references. The swap exchanges which node each field points to. No node is copied or moved in memory, so the subtrees keep their identity: a node that was
root.leftbefore the call isroot.rightafter it. - The return values of the recursive calls are ignored. Each call returns the node it was given, which is already in place, so there is nothing to assign.
this.invertTree. A recursive call to a method of the same class needs thethis.prefix.
Complexity
Time: O(n). The function is called once for each node and once for each missing child, at most 2n + 1 calls, with constant work in each.
Space: O(h), where h is the height of the tree, for the recursion stack. It is about log n for a balanced tree and n for a chain. The statement limits the height to 400 levels. No new nodes are created.
Edge cases and common mistakes
- Empty tree.
invertTree(null)returnsnullbefore any field is read. - A single node. The tree
[5]stays[5]: swapping twonullchildren changes nothing. - Nodes with one child.
[1, null, 2]becomes[1, 2]: the right child moves to the left. The swap works even when one side isnull. - Swapping with two separate assignments.
root.left = root.right; root.right = root.left;loses the old left child, because the second line copies the value that was just written. Use a temporary variable or the destructuring swap. - Swapping only at the root. Exchanging the root's children without recursing mirrors only the top level. Each subtree keeps its old orientation.
- Forgetting the base case. The recursion would reach a
nullchild and fail when it readsroot.leftofnull. - Expecting a copy. The tree is changed in place. After the call, the original variable holding the root sees the mirrored tree.
Testing
Level-order results, with null for a missing child and trailing nulls left out:
[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]gives[1, 3, 2].[1, null, 2]gives[1, 2].
