Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in Go: Recursive Swap of Children, O(n)

Practice O(n) Read the full explanation

You get the root of a binary tree. Turn it into its mirror image and return the root.

In the mirror image, every node's left and right children swap places. This is called inverting the tree.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as nil.

The test results print a tree in the same order, with spaces between the values. A missing child prints as -1, and the -1s at the end are left out. For example, [6,9,2,nil,7,4] prints as 6 9 2 -1 7 4. An empty tree prints as -1.

 

Example 1:

       6                     6
     /   \                 /   \
    2     9       →       9     2
     \   /                 \   /
      4 7                   7 4

Input: root = [6,2,9,nil,4,7]
Output: [6,9,2,nil,7,4]
Explanation: 2 and 9 swap places under the root.
4 moves from the right of 2 to its left.
7 moves from the left of 9 to its right.

Example 2:

  8                    8
   \                  /
    5       →        5
     \              /
      3            3

Input: root = [8,nil,5,nil,3]
Output: [8,5,nil,3]
Explanation: Every right child becomes a left child.
The chain now goes down to the left.

Example 3:

Input: root = [7]
Output: [7]
Explanation: A single node has no children to swap.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from 0 to 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you mirror the tree in O(n) time for n nodes, touching each node just once?
STEP 1 OF 5
    Ctrl + Enter to check

    GO · BINARY TREES

    Invert Binary Tree in Go, explained

    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

    1. Base case. If root == nil, return nil.
    2. 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.
    3. 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.
    4. Mirror the right side the same way with invertTree(root.Right). After both calls, every node below root has had its children swapped.
    5. 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.Right and then root.Right = root.Left overwrites 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.Left and root.Right changes 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 nil check comes first. Reading root.Left on a nil pointer 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 nil straight 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].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free