Skip to main content

226. Invert Binary Tree

easy

Mirror a binary tree by swapping every node's left and right subtrees. Famous as the question that prompted a viral 'we want our engineers to know this' tweet — a clean two-line recursive solve.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, invert the tree, and return its root.

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Examples

Example 1

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

Example 2

Input
root = [2,1,3]
Output
[2,3,1]

Example 3

Input
root = []
Output
[]

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Recurse: invert both subtrees, then swap them.

Hint 2

Base case: null returns null.

Hint 3

Iterative BFS or DFS works — swap children at every node visited.

Solution approach

Reveal approach

Recursive swap. If node is null, return null. Otherwise compute leftInverted = invert(node.left) and rightInverted = invert(node.right) — then assign node.left = rightInverted and node.right = leftInverted, and return node. Equivalent iterative version: BFS with a queue, popping each node and swapping its children before enqueueing them. O(n) time, O(h) space.

Complexity

Time
O(n)
Space
O(h)

Related patterns

  • dfs
  • recursion

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Google
  • Apple

Practice these live with InterviewChamp.AI

Drill Invert Binary Tree and Trees problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →