Invert Binary Tree


Invert Binary Tree – LeetCode


Problem: Invert Binary Tree

Problem Statement

Given the root of a binary tree, invert the tree, and return its root.

Inversion means swapping every left and right subtree recursively.


Examples

Example 1

Input:
       4
     /   \
    2     7
   / \   / \
  1   3 6   9

Output:
       4
     /   \
    7     2
   / \   / \
  9   6 3   1

Example 2

Input: root = []
Output: []


Constraints


Intuition

Inverting a binary tree means recursively swapping the left and right child of every node.

This problem is a classic example of post-order traversal (process children before the node).

We can solve it using either:


Approach 1: Recursive (Post-Order)

Algorithm

  1. If root is null → return null

  2. Recursively invert left and right subtrees

  3. Swap left and right pointers

  4. Return the root

Code (Java)

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;

        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        root.left = right;
        root.right = left;

        return root;
    }
}

Approach 2: Iterative (Level Order using Queue)

Algorithm

  1. Use a queue for level-order traversal.

  2. At each node, swap its left and right child.

  3. Add the children (if not null) to the queue.

Code (Java)

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;

        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);

        while (!q.isEmpty()) {
            TreeNode current = q.poll();

            // Swap left and right
            TreeNode temp = current.left;
            current.left = current.right;
            current.right = temp;

            if (current.left != null) q.add(current.left);
            if (current.right != null) q.add(current.right);
        }

        return root;
    }
}

Time and Space Complexity

For both approaches:


Dry Run (Recursive)

Input:

       1
     /   \
    2     3

Recursive call flow:


Conclusion