Invert Binary Tree

How to Invert Binary Tree or How to convert a binary tree into its mirror tree.

Given a binary tree, we have to write a code to invert it.

Inverting a Binary Tree

Inverting a binary tree means we have to interchange the left and right children of all non-leaf nodes. In simple words, Output is the mirror of the input tree.

Invert Binary Tree LeetCode

In this tutorial, I am going to discuss the iterative and recursive approaches to solve this problem.

How to convert a binary tree into it's mirror tree

For converting a binary tree into its mirror tree, we have to traverse a binary tree. Traversing a binary tree means visiting each node of a binary tree exactly once. It can be done through the depth-first (preorder, postorder and inorder) or breadth-first (level order) manner.

Level order traversal of a binary tree

Binary tree preorder traversal

Binary tree inorder traversal

At the end of this tutorial, I have shared the link to the video tutorial.

Invert binary tree video tutorial

Invert Binary Tree using Level Order Traversal – Java Code

In this section, I am going to discuss how we can solve this problem using the level order traversal of a binary tree. In level order traversal, We traverse a given binary tree level by level. And, To invert them interchange their left and right children of a node.

The time and space complexity of this approach is O(n).

Invert Binary Tree using Recursion | LeetCode Solution | Java Code

In the previous section, we have solved this problem iteratively. In this section, let’s discuss how we can convert a binary tree into its mirror tree using Recursion.

For solving this problem recursively we can either use preorder or postorder traversal.

In this example, I am using postorder traversal to solve this problem. In postorder traversal,

i) First, we traverse the left subtree of root in postorder.

ii) Then we traverse the right subtree of root in postorder.

iii) Finally we visit root.

The time complexity of this approach is O(n) and its space complexity is O(h) where h is the height of a binary tree.

Invert binary tree video tutorial

Data Structure Video Tutorials

Programming Questions on Arrays

Programming Questions on Linked List

Programming Questions on Binary Tree

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.