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≤ Number of nodes in the tree ≤100
- −1000≤
Node.value
≤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.