Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Invert Binary Tree

C++, Python and TypeScript solutions for Invert Binary Tree.

The Invert Binary Tree solutions are below.

Solution files

Python•invert-binary-tree/synced-solution.py
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def invertTree(root: TreeNode) -> TreeNode:
    if not root:
        return None

    root.left, root.right = root.right, root.left
    invertTree(root.left)
    invertTree(root.right)

    return root
C++•invert-binary-tree/synced-solution.cpp
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return nullptr;

        swap(root->left, root->right);
        invertTree(root->left);
        invertTree(root->right);

        return root;
    }
};
TypeScript•invert-binary-tree/synced-solution.ts
function invertTree(root: TreeNode | null): TreeNode | null {
    if (!root) return null;

    [root.left, root.right] = [root.right, root.left];
    invertTree(root.left);
    invertTree(root.right);

    return root;
}