All coding questions

Invert Binary Tree

easy
Blind 75NeetCode 150treesrecursion

Problem

Given the root of a binary tree, produce its mirror image by swapping the left and right child of every node. Return the root of the inverted tree.

Examples

Input: [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Every node's children are swapped.
Input: empty tree
Output: empty tree
Nothing to invert.

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= node value <= 100
Hints(tap to reveal)
  • 1. Swap children at each node.
  • 2. Recurse into both subtrees.
Optimal approach(spoiler)
  1. If the node is null, return null.
  2. Swap the node's left and right children.
  3. Recurse into both subtrees.
  4. Return the original root after the swaps propagate.
  5. O(n) time, O(h) recursion space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor