AlgoMaster Logo

Invert Binary Tree

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The recursive approach is elegant and leverages the natural recursive structure of trees. The idea is to swap the left and right children of a node recursively. For each node, invert the left subtree and the right subtree. This results in a mirrored version of the original tree.

Code:

2. Iterative Approach Using BFS

Intuition:

We can also solve this problem iteratively using a breadth-first search (BFS) approach. The idea is to use a queue to perform a level-order traversal of the tree. At each node, swap the left and right children.

Code:

3. Iterative Approach Using DFS with Stack

Intuition:

Another iterative method is using depth-first search (DFS) with a stack. Similar to BFS, traverse the tree and swap left and right children for each node encountered.

Code: