Question: Given a binary tree, find its mirror tree.
Input: A tree pointer is given. (Root pointer)
Output: Pointer of mirrored tree.
We can easily get the mirrored tree by a simple recursive algorithm. We traverse the tree and swap the left and right pointers.
#include<stdio.h> #include<malloc.h> struct binaryTreeNode{ int data; struct binaryTreeNode * left; struct binaryTreeNode * right; }; struct binaryTreeNode * mirrorOfBinaryTree(struct binaryTreeNode * root) { struct binaryTreeNode * temp; if(root) { mirrorOfBinaryTree(root -> left); mirrorOfBinaryTree(root -> right); // Swap the pointers in this node temp = root -> left; root -> left = root -> right; root -> right = temp; } return root; }
Time Complexity:- O(n)
Space Complexity:- O(n) (due to recursive stack)