C program to create a mirror of the binary tree

In this tutorial, we will learn how to create a mirror of the binary tree using C program? By Nidhi Last updated : August 10, 2023

Problem statement

Create a binary tree, and then create a mirror of the created binary tree.

C program to create a mirror of the binary tree

The source code to create a mirror of the binary tree is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to create a mirror of
// binary tree

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int item;
    struct node* left;
    struct node* right;

} Node;

void AddNode(Node** root, int item)
{
    Node* temp = *root;
    Node* prev = *root;

    if (*root == NULL) {
        *root = (Node*)malloc(sizeof(Node));

        (*root)->item = item;
        (*root)->left = (*root)->right = NULL;
    }
    else {
        while (temp != NULL) {
            if (item > temp->item) {
                prev = temp;
                temp = temp->right;
            }
            else {
                prev = temp;
                temp = temp->left;
            }
        }
        temp = (Node*)malloc(sizeof(Node));
        temp->item = item;

        if (item >= prev->item)
            prev->right = temp;
        else
            prev->left = temp;
    }
}

void Inorder(Node* root)
{
    if (root != NULL) {
        Inorder(root->left);
        printf("%d ", root->item);
        Inorder(root->right);
    }
}

void createMirrorTree(Node* root)
{
    Node* temp;

    if (root == NULL)
        return;

    createMirrorTree(root->left);
    createMirrorTree(root->right);

    temp = root->left;
    root->left = root->right;
    root->right = temp;
}

int main()
{
    Node* root = NULL;

    AddNode(&root, 10);
    AddNode(&root, 20);
    AddNode(&root, 60);
    AddNode(&root, 50);
    AddNode(&root, 40);

    printf("Tree Items: (INORDER) \n");
    Inorder(root);

    createMirrorTree(root);

    printf("\nMirror Tree items: (INORDER)\n");
    Inorder(root);
    printf("\n");

    return 0;
}

Output

Tree Items: (INORDER) 
10 20 40 50 60 
Mirror Tree items: (INORDER)
60 50 40 20 10

Explanation

Here, we created a self-referential structure to implement a Binary Tree, a function to add a node into the binary tree, and a recursive function createMirrorTree() to create the mirror tree of the created tree.

In the main() function, we created a binary search tree, and called the function createMirrorTree() to create a mirror tree and printed the items of the mirror tree.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.