Invert Binary Tree [Easy]

22 Aug 2026, Updated: 25 Sep 2026 2 min read
3
The Invert Binary Tree problem requires swapping the left and right children of every node in a binary tree.

Problem

Given the root of a binary tree, invert the tree and return its root. Inverting a binary tree means swapping the left and right child of every node.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

root = [4,2,7,1,3,6,9]

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

Output

root = [4,7,2,9,6,3,1]

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

Solution

This solution uses Depth-First Search (DFS) with recursion. For each node, its left and right children are swapped.

The same process is then applied recursively to both subtrees. When a null node is reached, the recursion stops.

After all nodes have been processed, the entire binary tree is inverted.
class Solution {

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

        // Recursively invert both subtrees
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);

        // Swap left and right subtrees
        root.left = right;
        root.right = left;

        return root;
    }
}

Complexity

Each node in the binary tree is visited exactly once, resulting in a time complexity of O(n).

The recursive call stack can grow up to the height of the tree, resulting in an extra space complexity of O(h), where h is the height of the tree.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion