Problem overview
invertTree receives the root of a binary tree, a TreeNode?, 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 node class: a TreeNode has an Int field value and two nullable children, left and right.
The tree [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1]. First 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
Mirroring a tree means swapping the two children of the root and then mirroring each of those subtrees. Each subtree is a binary tree, so the same function can do it. That is a recursive solution with the empty tree as the base case.
The function changes the tree in place: it does not build a new one. It visits every node once, so the time is O(n) for n nodes.
Step by step
- Handle the empty tree. If
root == null, returnnull. This also stops the recursion when it steps past a leaf. - Save the left child in a
valnamedtemp. The next line overwritesroot.left, andtempkeeps the old left child so it isn't lost. - Finish the swap. Set
root.lefttoroot.right, androot.righttotemp. The two 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 node it returns is not needed. - Mirror the right subtree the same way.
- Return
root. It is still the top of the tree, which is now mirrored.
The solution in Kotlin
class Solution {
fun 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
}
}
Some Kotlin details in this code:
- After the
if (root == null)check that returns, Kotlin knowsrootis notnull(a smart cast), soroot.leftandroot.rightneed no?.. - The children have the type
TreeNode?, sotemphas that type too, and assigning it back toroot.rightis allowed. - Calling
invertTree(root.left)as a statement and ignoring its return value is fine in Kotlin. The function's work is the swapping it does along the way. - The tree is changed where it stands. The returned node is the same object as the argument: for
[1,2,null,3],invertTree(t) === tistrue.
Following the first example
Printing the tree in level order before and after the call:
4,2,7,1,3,6,9
4,7,2,9,6,3,1
The root 4 swaps its children, so 7 is now on the left and 2 on the right. The recursion then swaps the children of 7 (6 and 9 become 9 and 6) and of 2 (1 and 3 become 3 and 1).
Complexity
Time: O(n). Every node is visited once, and each visit does a constant amount of work: one swap and two calls.
Space: O(h), where h is the height of the tree. The recursion keeps one call open per level of the current path: about log n for a balanced tree and n for a chain. The lesson's trees are at most 400 levels deep.
Edge cases and common mistakes
- Empty tree.
nullcomes back asnull. - A single node. Both children are
null, so swapping changes nothing. - Only one child. A node with a left child and no right child ends up with a right child and no left one. In
[5,1]the 1 moves to the right side. - Losing a subtree. Writing
root.left = root.rightand thenroot.right = root.leftwithouttempmakes both children the same node, and the original left subtree is gone. - Skipping the recursion. Swapping only the root's children gives a tree whose lower levels are not mirrored. Every node needs its own swap.
Testing
[4,2,7,1,3,6,9] -> [4,7,2,9,6,3,1]
[1,2,null,3] -> [1,null,2,null,3]
[5,1] -> [5,null,1]
[] -> []
