InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Invert Binary Tree

easy Original ↗ 00:00

Problem

Given the root of a binary tree, produce its mirror image: at every node, the left and right children swap places. Return the root of the inverted tree (modifying the tree in place is fine).

Examples

Example 1

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

        4                 4
       / \               / \
      2   7     →       7   2
     / \ / \           / \ / \
    1  3 6  9         9  6 3  1

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

Every left/right pair is swapped, at every depth.

Example 2

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

The two leaves trade places under the root.

Example 3

Input:  root = []
Output: []

An empty tree is its own mirror.

Constraints

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

Think about it first

Hint 1 What does the mirror of a tree look like in terms of the mirrors of its two subtrees?
Hint 2 Mirror(root) = a node whose left child is Mirror(right subtree) and whose right child is Mirror(left subtree). That is the entire recursion.
Hint 3 Equivalently: visit every node in any order (stack or queue) and swap its two child pointers. The traversal order doesn't matter because each swap is local.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug