Start learning free

LESSON 206 OF 314 · BINARY TREES

Invert Binary Tree in C#: Swap Children Recursively, 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 null.

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,null,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,null,4,7]
Output: [6,9,2,null,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,null,5,null,3]
Output: [8,5,null,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

    C# · BINARY TREES

    Invert Binary Tree in C#, explained

    Problem overview

    The method InvertTree 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 child and the right child trade places, all the way down to the leaves.

    The lesson provides the TreeNode class: an int val and two TreeNode fields, left and right, which are null for a missing child. A node is created with new TreeNode(x).

    The tree [4,2,7,1,3,6,9], listed level by level, becomes [4,7,2,9,6,3,1]. Under the root, 2 and 7 swap, then 1 and 3 swap under 2, and 6 and 9 swap under 7. For [1,2,null,3], a line of nodes going left becomes a line going right. An empty tree is its own mirror. The tests print a tree level by level with -1 for a missing child and trailing missing children left out, so the first result prints as 4 7 2 9 6 3 1.

    Approach: swap, then mirror each side

    A mirror image of a tree has the two subtrees of the root exchanged, and each of those subtrees is itself mirrored. So the method has three parts for a node: swap its two children, mirror the subtree that is now on the left, and mirror the subtree that is now on the right.

    The recursion stops at an empty tree. A null node has nothing to swap and is returned as it is. Because every leaf has two null children, this base case is reached at the bottom of every path.

    The tree is changed in place. No new nodes are made, and the method returns the same root it received, because the root is still at the top. Each node is visited once, so the time is O(n) for n nodes.

    The order inside the method doesn't matter much. Swapping first and recursing after, as here, works, and so does recursing into both children first and swapping afterwards. What matters is that every node gets swapped exactly once.

    Running the method on some trees prints these level-order results, before and after:

    4 2 7 1 3 6 9  =>  4 7 2 9 6 3 1
    1 2 -1 3  =>  1 -1 2 -1 3
    -1  =>  -1
    5  =>  5
    1 2 3  =>  1 3 2
    

    Step by step

    1. Write the base case. If root == null, return null. An empty tree is its own mirror, and this check also stops the recursion after a leaf.
    2. Swap the children in one line with a tuple assignment: (root.left, root.right) = (root.right, root.left);. The right-hand tuple is built first from the old children, so neither is lost.
    3. Mirror the left subtree by calling InvertTree(root.left). It swaps the children all the way down that subtree in place, so the returned node doesn't need to be kept.
    4. Mirror the right subtree with InvertTree(root.right) in the same way.
    5. Return root, the top of the now mirrored tree.

    The solution in C#

    class Solution {
        public TreeNode InvertTree(TreeNode root) {
            if (root == null) {
                return null;
            }
            (root.left, root.right) = (root.right, root.left);
            InvertTree(root.left);
            InvertTree(root.right);
            return root;
        }
    }
    

    The C# details worth knowing:

    • Tuple assignment swaps without a temporary variable. (a, b) = (b, a) evaluates the right side first and then assigns both targets. With a = 1 and b = 2 it leaves a as 2 and b as 1. It works on fields such as root.left just as well as on local variables.
    • Two plain assignments don't swap. n.left = n.right; n.right = n.left; on a node with children 2 and 3 leaves both children as 3, because the first line overwrites the left child before the second line reads it. Without a tuple you need a temporary variable.
    • The returned values of the recursive calls are ignored. This is fine because the calls modify the nodes in place, and each child is still the same object after its call. The return value matters only for the top-level call.
    • Nodes are references. The tree handed back is the same object graph as the one passed in: the returned root is the same object as the argument. Anyone else holding the old tree sees it mirrored too.
    • Field names are lowercase. The provided TreeNode has val, left and right. Use those exact names.

    Complexity

    Time: O(n). Each node is swapped once, and each missing child costs one call that returns at once.

    Space: O(h), where h is the height of the tree, for the call stack. A balanced tree needs about log n frames, and a chain where every node has one child needs n. The lesson's trees are at most 400 levels deep.

    Edge cases and common mistakes

    • Empty tree. The method returns null, which prints as -1.
    • A single node. Swapping two null children changes nothing, and the tree prints as 5.
    • Missing children. A node with only a left child ends up with only a right child. [1,2,null,3] becomes the level order 1 -1 2 -1 3.
    • Swapping only at the root. Then just the top two subtrees trade places and the insides stay as they were. Every level has to be mirrored.
    • Swapping twice. Mirroring a subtree and then swapping the children of the same node again undoes the work. Swap once per node.
    • Swapping with two assignments. As shown above, that loses one child. Use the tuple or a temporary variable.
    • Forgetting return root. The tree is already mirrored in place, but the caller would get nothing back, and the code would not compile for a method with a return type.

    Testing

    These trees were run through the method and printed level by level with -1 for a missing child.

    • [4,2,7,1,3,6,9] gives 4 7 2 9 6 3 1.
    • [1,2,null,3] gives 1 -1 2 -1 3.
    • An empty tree gives -1.
    • [5] gives 5.
    • [1,2,3] gives 1 3 2.
    • For a chain of 10,000 left children, the root ends up with no left child and a right child.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free