Home Trees Given a binary tree, construct its mirror tree.

# Given a binary tree, construct its mirror tree.

0 comment

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)

0 comment

#### You may also like

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More