150NeetCode 150

46.Invert Binary Tree

EasyBlind 75Trees ยท 1/15

Problem

Given the root of a binary tree, invert the tree and return its root. Inverting means mirroring the tree left-to-right: at every node, the left child and the right child swap places.

The values themselves never move between nodes โ€” only the left / right pointers change.

Examples

Input:  root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Explanation: Every level is read in reverse order after mirroring.
Input:  root = [2,1,3]
Output: [2,3,1]
Input:  root = []
Output: []
Explanation: An empty tree is its own mirror.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

๐Ÿ’ก Key Insight

The mirror of a tree is obtained by swapping the children of every node โ€” the order in which nodes are visited does not matter, as long as each node is visited exactly once. So any traversal works: a queue (BFS), an explicit stack (DFS), or plain recursion. Each runs in O(n); they only differ in what the auxiliary space depends on (width vs. height).

BFS with a Queue

TimeO(n)SpaceO(w)

Intuition

Visit the tree level by level. Whenever a node is dequeued, swap its two children, then enqueue those children so they get swapped too. Since every node is processed once, the whole tree ends up mirrored.

Algorithm

  1. If root is null, return null.
  2. Push root into a queue.
  3. While the queue is not empty:
    • Poll a node, swap node.left and node.right.
    • Enqueue each non-null child.
  4. Return root.

Visualization

Queue processing on [4,2,7,1,3,6,9]

poll 4 -> swap (2,7) -> children now (7,2)   queue: [7, 2]
poll 7 -> swap (6,9) -> children now (9,6)   queue: [2, 9, 6]
poll 2 -> swap (1,3) -> children now (3,1)   queue: [9, 6, 3, 1]
poll 9, 6, 3, 1 -> leaves, swapping null/null changes nothing

Code

java
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            // mirror this node
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
        return root;
    }
}

Complexity

  • Time: O(n) โ€” every node is enqueued and swapped exactly once.
  • Space: O(w) โ€” the queue holds at most one level; for a complete tree the last level has about n/2 nodes, so O(n) worst case.

Complexity Comparison

Approach Time Space
BFS with a Queue O(n) O(w) โ€” up to O(n)
Iterative DFS with a Stack O(n) O(h)
Recursive DFS O(n) O(h)

Common Pitfalls

  • Writing root.left = invertTree(root.right); root.right = invertTree(root.left); โ€” the second line reads the already overwritten root.left. Save the results in temporaries first.
  • Forgetting the null root case โ€” calling methods on null throws a NullPointerException.
  • Swapping only the root's children (or only one level); every node in the tree must be swapped.
  • Creating new nodes instead of re-pointing existing ones is allowed but wastes O(n) memory for no benefit.