15 Jun 2024C++ / Python / TypeScriptEasy

Invert Binary Tree

Collected C++, Python, TypeScript solutions for invert binary tree. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Invert Binary Tree. the solution files are available below.

solution files

  • C++ invert-binary-tree/synced-solution.cpp
  • Python invert-binary-tree/synced-solution.py
  • TypeScript invert-binary-tree/synced-solution.ts

Solution files

Pythoninvert-binary-tree/synced-solution.py
class TreeNode:
    def __init__(self, val=class="syntax-number">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;
    }
};
TypeScriptinvert-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;
}