← Back to Codes

2026-06-09 16:36:42

Invert Binary Tree in Python and Java | LeetCode #226

Learn how to solve Invert Binary Tree in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Invert Binary Tree in Python and Java

In this tutorial, we will learn LeetCode #226: Invert Binary Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Invert Binary Tree Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use recursive swapping because it gives a clean and optimized solution.

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

Expected result:
Output: [4,7,2,9,6,3,1]

Explanation:
Left and right children are swapped.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
root = [4,2,7,1,3,6,9]

Approach:
recursive swapping

We update variables step by step until we reach:
Output: [4,7,2,9,6,3,1]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why recursive swapping is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

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

We will solve it using recursive swapping.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: [4,7,2,9,6,3,1]

Why?
Left and right children are swapped.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: [4,7,2,9,6,3,1]

Example 1

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

Output:
Output: [4,7,2,9,6,3,1]

Explanation:
Left and right children are swapped.

Example 2

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

Output:
[4,7,2,9,6,3,1]

Explanation:
Every left and right child is swapped.

Python Code

Here is the complete Python solution for LeetCode #226.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class BinaryTreeInverter:
    def invert_tree(self, root):
        if not root:
            return None

        root.left, root.right = self.invert_tree(root.right), self.invert_tree(root.left)
        return root


def preorder(root):
    if not root:
        return []
    return [root.val] + preorder(root.left) + preorder(root.right)


root = TreeNode(4, TreeNode(2), TreeNode(7))
inverter = BinaryTreeInverter()
print(preorder(inverter.invert_tree(root)))  # Output: [4, 7, 2]

Java Code

Here is the complete Java solution for LeetCode #226.

import java.util.ArrayList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) { this.val = val; }
}

class BinaryTreeInverter {
    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;
    }

    private static void preorder(TreeNode root, List<Integer> values) {
        if (root == null) return;
        values.add(root.val);
        preorder(root.left, values);
        preorder(root.right, values);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);

        BinaryTreeInverter inverter = new BinaryTreeInverter();
        List<Integer> values = new ArrayList<>();
        preorder(inverter.invertTree(root), values);
        System.out.println(values); // [4, 7, 2]
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #226: Invert Binary Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.