Problem overview
invertTree receives the root of a binary tree, mirrors it 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 node class. A TreeNode is created with a value, TreeNode(4), and has two fields, left and right, which hold the children or null. The lesson's tests print a tree in level order with spaces between the values, using -1 for a missing child and leaving out trailing ones.
The tree [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1]: 2 and 7 trade places 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. The follow-up asks for O(n) time, visiting each node once.
Approach: swap at one node, then trust the recursion
Think about a single node. To mirror the tree under it, swap its two children, then mirror the subtree under each child. Both subtrees are smaller trees of the same kind, so the same method does the job, and the recursion works its way down to the leaves.
The base case is an empty tree, null. It has nothing to swap, and it is where the recursion stops after stepping past a leaf.
The order of the swap and the two recursive calls does not matter for the result. Mirroring the children first and swapping afterwards produces the same tree. The lesson swaps first, so after the swap the two recursive calls handle the subtree that is now on the left and the one that is now on the right.
The method changes the tree in place and returns the same root node it received. No new nodes are created.
Step by step
- Base case. If
root == null, returnnull. - Save the left child.
val temp = root.leftkeeps the old left child. The next line overwritesroot.left, and withouttempthat subtree would be lost. - Finish the swap.
root.leftbecomesroot.right, androot.rightbecomestemp. The two children have traded places. - Mirror the left subtree. Call
invertTree(root.left). The call swaps children all the way down that subtree, in place, so the returned node isn't needed. - Mirror the right subtree with
invertTree(root.right). Afterwards every node belowroothas had its children swapped. - Return
root. It is still the top of the tree, which is now mirrored.
The solution in Scala
class Solution {
def invertTree(root: TreeNode): TreeNode = {
if (root == null) {
return null
}
val temp = root.left
root.left = root.right
root.right = temp
invertTree(root.left)
invertTree(root.right)
return root
}
}
The Scala details worth a closer look:
- Fields are assignable.
root.left = root.rightworks because the lesson declaresleftandrightasvars. Avalfield could not be reassigned. - Parameters are not variables.
rootitself cannot be reassigned, but the object it refers to can change. The method relies on that: it modifies the node's fields, not the parameter. - The result of a recursive call is ignored.
invertTree(root.left)returns aTreeNodethat the code throws away. This is legal as a statement. It is safe here because the call returns the same node it was given, already mirrored in place. - Return type. A recursive method needs its result type spelled out, as
: TreeNodehere. Bothreturn nullandreturn rootfit it, becausenullis a validTreeNodevalue for this class. val temp. The temporary is assigned once, so it is aval.
Complexity
Time: O(n). The method is called once for each node, and once for each missing child, which adds at most n + 1 calls. Each call does a constant amount of work apart from the recursive calls.
Space: O(h), where h is the height of the tree, for the stack of active calls. A balanced tree uses about log n frames, and a line of n nodes uses n. The lesson promises at most 400 levels.
Edge cases and common mistakes
- An empty tree.
invertTree(null)returnsnull, which the tests print as-1. - A single node. Both children are
null, the swap changes nothing, and the tree prints as it was:7stays7. - A line of nodes.
[1,2,null,3]prints as1 2 -1 3before the call and1 -1 2 -1 3after it. - Swapping without
temp. Writingroot.left = root.rightfollowed byroot.right = root.leftsets both children to the old right child. For a root with children 2 and 3, both end up as 3, and the 2 is lost. - Skipping the recursive calls. Only the root's two children would swap, and everything below them would keep its old orientation.
- Inverting twice. The second call restores the original tree. Inverting
[2,1,3]twice prints2 1 3. - Expecting a new tree. The original tree is changed. After the call, the variable that held the old root sees the mirrored tree, and the returned node is that same node.
Testing
[4,2,7,1,3,6,9]prints4 2 7 1 3 6 9before the call and4 7 2 9 6 3 1after it.[1,2,null,3]becomes1 -1 2 -1 3.[1,2,3]becomes1 3 2, and the returned node is the same object as the root passed in.[7]stays7.- An empty tree returns
null.
