Skip to main content

How to Invert A Binary Tree (Iteratively + Recursively)?

Inverting a binary is one of the most common questions being asked these days. Often, seen many times in the ad of AlgoExpert as well.

So, what is an inverted binary tree?
Inverted binary tree is a simply a mirror image of given binary tree.
Example :


So, all we need to do is "Swapping left children with right children of a binary tree at every level."

Implementation

Recursively

 TreeNode* invertTree(TreeNode* root) 
{
if(root==NULL)
return NULL;
swap(root->left,root->right);
invertTree(root->left);
invertTree(root->right);

return root;
}
Iteratively
TreeNode* invertTree(TreeNode* root) 
{
if(root==NULL)
return NULL;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* c= q.front();
q.pop();
swap(c->left,c->right);
if(c->left!=NULL)
q.push(c->left);
if(c->right!=NULL)
q.push(c->right);
}
return root;
}

I hope this tutorial helped you!
Happy Coding!

Comments