# Solution: Invert Binary Tree

Let's solve the Invert Binary Tree problem using the Tree Depth-first Search pattern.

We'll cover the following

## Statement

Given the root node of a binary tree, transform the tree by swapping each nodeâ€™s left and right subtrees, thus creating a mirror image of the original tree. Return the root of the transformed tree.

Constraints:

• $0\leq$ Number of nodes in the tree $\leq 100$
• $-1000 \leq$ Node.value $\leq 1000$

## Solution

For this solution, we do a post-order (left, right, parent) traversal of the binary tree. The algorithm is as follows:

• Perform post-order traversal on the left child of the root node.
• Perform post-order traversal on the right child of the root node.
• Swap the left and right children of the root node.

Since we perform a depth-first search traversal, the children of any node are already mirrored even before we return the node itself.

Letâ€™s look at an example below:

Note: In this example, the node at the top of the stack is the current node.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.