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 hel
Developers Nest - Intensify Your Coding Skills
Learn Coding For Free, Level Up Your Coding Skills, Prepare Mostly Asked Interview Questions, Developers Nest, Eat Sleep Code Repeat, Intensify Your Coding Skills