AAlgoLoopSpaced repetition for LeetCode
EASYTree / RecursionLeetCode ↗

Invert Binary Tree

The key idea

Inverting a tree just means swapping the left and right child of every node. Solve it the same way you would describe it recursively: swap the two children of the current node, then invert each of the two subtrees. The node values never change — only the links between parents and children do.

Problem

You are given the root of a binary tree. Invert the tree and return its root.

To invert a binary tree, you turn it into its mirror image: at every node, its left subtree and right subtree are swapped. The values stored in the nodes stay the same — only the left/right position of each child changes.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems