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:
- Number of nodes in the tree
-
Node.value
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 80+ hands-on prep courses.