Problem overview
The function invertTree receives root, a pointer to the top node 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 TreeNode type, with an integer Val and pointers Left and Right, which are nil for a missing child.
The tree [4, 2, 7, 1, 3, 6, 9], written in level order, has 4 at the top, 2 and 7 below it, then 1, 3, 6 and 9. After inverting, it reads [4, 7, 2, 9, 6, 3, 1]. A tree [1, 2, nil, 3], a line of nodes going left, becomes [1, nil, 2, nil, 3], a line going right. An empty tree is its own mirror. The test results print a tree in level order with -1 for a missing child and the trailing ones left out, so the empty tree prints as -1.
The follow-up asks for O(n) time, visiting each node once.
Approach: swap, then mirror both subtrees
The mirror of a tree is the tree with the two children of the root swapped, where each child's subtree has been mirrored too. That definition is recursive: swap the children of a node, then do the same for the subtree on each side.
The recursion stops at an empty tree, a nil pointer. There is nothing to swap in it, and it also covers the missing children below a leaf. The algorithm changes the tree in place. It creates no new nodes and rewires the pointers of the existing ones, so the root it returns is the same node it received.
Step by step
- Base case. If
root == nil, returnnil. - Swap the children. A single assignment,
root.Left, root.Right = root.Right, root.Left, does it. Go evaluates the whole right side before assigning anything, so neither child is lost. - Mirror the left side. Call
invertTree(root.Left). After the swap, this is the subtree that used to be on the right, and it still needs its own children swapped. The call works in place, so the node it returns doesn't need to be kept. - Mirror the right side the same way with
invertTree(root.Right). After both calls, every node belowroothas had its children swapped. - Return
root. It is still the top of the tree, which is now mirrored.
The solution in Go
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}
Run on [4, 2, 7, 1, 3, 6, 9], the function returns the same root node, and the tree reads [4, 7, 2, 9, 6, 3, 1] in level order. On [1, 2, nil, 3] it gives [1, nil, 2, nil, 3]. On an empty tree it returns nil.
Go details
- Tuple assignment is the swap. Go has no need for a temporary variable. In
a, b = b, a, both values on the right are computed first, then assigned. The same works for fields. - Two separate assignments would break it. Writing
root.Left = root.Rightand thenroot.Right = root.Leftoverwrites the left child first, so both pointers end up at the old right child. For a root with children 2 and 7, both sides then hold 7, and the 2 is lost. - Pointers, so the change is shared. The function receives a copy of the pointer, but the nodes it points to are the caller's own. Changing
root.Leftandroot.Rightchanges the tree the caller holds. - The ignored results. Go lets you call a function and drop its return value, so
invertTree(root.Left)as a statement is fine. - The
nilcheck comes first. Readingroot.Lefton anilpointer panics, so the base case must run before the swap.
Complexity
Time: O(n). Every node is visited once, and each visit does one swap. The nil children add at most n + 1 calls that return at once.
Space: O(h), where h is the height of the tree. No new nodes are made, and the only extra memory is the recursion stack, one frame per level on the current path.
Edge cases and common mistakes
- Empty tree. The function returns
nilstraight away. - A single node. Both children are
nil, so the swap changes nothing, and the same node is returned. - A line of nodes.
[1, 2, nil, 3]becomes a line going right, and a node that only had a left child ends up with only a right child. - Swapping only at the root. This mirrors the top level and leaves the subtrees as they were. The recursive calls are what carry the swap down.
- Losing a child. Assigning one child and then the other, without the tuple assignment, leaves both pointers at the same node.
- Inverting twice. It gives the original tree back, which makes a handy check.
- Using the result of the recursive calls. You can, but with an in-place swap you don't need to: the nodes are already rewired.
Testing
[4, 2, 7, 1, 3, 6, 9]gives[4, 7, 2, 9, 6, 3, 1].[1, 2, nil, 3]gives[1, nil, 2, nil, 3].- An empty tree gives an empty tree.
[5]gives[5].- Inverting
[4, 2, 7, 1, 3, 6, 9]twice gives[4, 2, 7, 1, 3, 6, 9].
