Design Gurus Logo
Blind 75
Solution: Invert Binary Tree

Problem Statement

Given the root of a binary tree, invert it.

Example:

Given the following two binary trees:

Image

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -100 <= Node.val <= 100

Solution

This problem is quite similar to Same Tree. We can follow the same approach. After swapping left and right child of a node, we will recursively invert its left and right subtrees.

Code

Here is what our algorithm will look like:

Python3
Python3

Time Complexity

Since we traverse each node once, the solution will take O(N) time where 'N' is the total number of nodes in the tree.

Space Complexity

We will need O(N) space for the recursion stack in the worst case (when the binary tree is a list). Overall, we will need to store nodes equal to the height of the tree, hence, O(H) space complexity, where H is the height of the given tree.

Making the Algorithm Multi-threaded

To further improve the algorithm, we can make invertTree() multi-threaded to invert left and right subtrees in separate threads.

We can find how many cores the machine has on which our algorithm is running. We will, then, start multiple threads so that each core can run one thread.

Here is the code that takes care of this scenario:

Python3
Python3

Time and Space Complexities

Everything has the same complexity as the previous solution.