Algo-Sim › Binary Trees & BST

Invert Binary Tree

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Mirror the tree: invert both subtrees, then swap them. Every node is visited once.

Problem

Mirror a binary tree: swap the left and right child of every node. Return the root of the inverted tree.

Constraints

Edge cases to test

Follow-up questions

Recursive or iterative?
Either visits each node once. BFS with a queue avoids deep recursion on a skewed tree.
How do you check two trees are mirrors?
Compare left with right recursively (Symmetric Tree, LC 101).

Solution

Java

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;
}

Python

def invert_tree(root):
    if not root:
        return None
    left = invert_tree(root.left)
    right = invert_tree(root.right)
    root.left, root.right = right, left
    return root

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    TreeNode *invertTree(TreeNode *root) {
        if (root == nullptr)
            return nullptr;
        TreeNode *left = invertTree(root->left);
        TreeNode *right = invertTree(root->right);
        root->left = right;
        root->right = left;
        return root;
    }
};

More Binary Trees & BST problems