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.
1 of 16
2 of 16
3 of 16
4 of 16
5 of 16
6 of 16
7 of 16
8 of 16
9 of 16
10 of 16
11 of 16
12 of 16
13 of 16
14 of 16
15 of 16
16 of 16
Let’s look at the code for this solution below:
Time complexity#
The time complexity of this solution is linear, , where is the number of nodes in the tree.
Note: Every subtree needs to be mirrored, so we visit every node once. Because of that, the runtime complexity is .
Space complexity#
The space complexity of this solution is , where is the height of the tree. This is because our recursive algorithm uses space on the call stack, which can grow to the height of the binary tree. The complexity will be for a balanced tree and for a degenerate tree.
Invert Binary Tree
Maximum Depth of Binary Tree