DSA Visualizer · 25 visualizationsInvert Binary Tree
EasyTrees

Invert Binary Tree

Given the root of a binary tree, invert the tree (mirror it), and return its root. Recursive approach: To invert, swap the left and right children at every node, then recursively invert both subtrees. The base case is when the node is null.

The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(h) — call stack
def invertTree(root):
    if not root:
        return None
    # Swap children
    root.left, root.right = root.right, root.left
    # Recurse on both subtrees
    invertTree(root.left)
    invertTree(root.right)
    return root
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough