Given a binary tree, write an efficient algorithm to invert it.

For example,

Invert Binary Tree

Practice this problem

Recursive Solution

This is one of the most famous interview questions and can be easily solved recursively. The idea is to traverse the tree in a preorder fashion, and for every node encountered, swap its left and right child before recursively inverting its left and right subtree. We can also traverse the tree in a postorder fashion.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

1 3 7 6 2 5 4

Java


Download  Run Code

Output:

1 3 7 6 2 5 4

Python


Download  Run Code

Output:

1 3 7 6 2 5 4

The time complexity of the above recursive solution is O(n), where n is the total number of nodes in the binary tree. The program requires O(h) extra space for the call stack, where h is the height of the tree.

Iterative Solution

We can easily convert the above recursive solution into an iterative one using a queue or stack to store tree nodes.

1. Using Queue:

The code is almost similar to the level order traversal of a binary tree. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 3 7 6 2 5 4

Java


Download  Run Code

Output:

1 3 7 6 2 5 4

Python


Download  Run Code

Output:

1 3 7 6 2 5 4

2. Using Stack:

The code is almost similar to the iterative preorder traversal of a binary tree. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

1 3 7 6 2 5 4

Java


Download  Run Code

Output:

1 3 7 6 2 5 4

Python


Download  Run Code

Output:

1 3 7 6 2 5 4

The time complexity of both above-discussed iterative methods is O(n), where n is the total number of nodes in the binary tree. The program requires O(n) extra space for storing nodes present in any level of the binary tree. The worst case happens for a full binary tree, in which the last level has n/2 nodes.