Mirror of a tree

Pattern: Depth, diameter and balance

medium

To mirror a tree, swap the left and right children of every node. Any order of visiting works, as long as every node is swapped exactly once.

The problem

Change the tree in place into its mirror image: left and right swapped at every node. [1, 3, 2] becomes [1, 2, 3]. The function returns nothing; the tests print the tree. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What happens at a single node?
  • What about the subtrees below it?
  • Does the order of visiting matter?

Hints

    Brute force, and why it fails

    Build a new mirrored tree and copy it back: twice the memory.

    The key insight

    Mirroring is a swap at every node, so any traversal that touches each node once does it.

    Dry run

    tree[1, 2, 3]

    [1, 3, 2]. Swap the root's children: 2 on the left, 3 on the right.

    Step 1 of 2

    The plan

    mirror(n): if null: return
               swap n.left, n.right
               mirror(n.left); mirror(n.right)
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each node is swapped once.

    Edge cases

    • Empty tree.
    • One node.
    • A long chain, where recursion is n deep.
    I've built my logic, show the code

    Java

    class Solution {
        public void mirror(TreeNode node) {
            if (node == null) return;
            TreeNode t = node.left;                 // swap the children ...
            node.left = node.right;
            node.right = t;
            mirror(node.left);                      // ... and mirror below them
            mirror(node.right);
        }
    }

    C++

    class Solution {
    public:
        void mirror(TreeNode* node) {
            if (node == NULL) return;
            swap(node->left, node->right);          // swap the children ...
            mirror(node->left);                     // ... and mirror below them
            mirror(node->right);
        }
    };

    Python

    class Solution:
        def mirror(self, node) -> None:
            if node:
                node.left, node.right = node.right, node.left   # swap the children ...
                self.mirror(node.left)              # ... and mirror below them
                self.mirror(node.right)

    Common mistakes

    • Swapping and then recursing into the same child twice.
    • Swapping only the root.

    Similar problems