Logo
Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Solution: Invert Binary Tree

Problem Statement

Given the root of a binary tree, invert it.

Example:

Given the following two binary trees:

Constraints:

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

Solution

This problem is quite similar to Same Tree. We can follow the same approach. After swapping left and right child of a node, we will recursively invert its left and right subtrees.

Code

Here is what our algorithm will look like:

.....

.....

.....

Like the course? Get enrolled and start learning!