In this program, we are going to share a C program to create a mirror copy of a tree and display using BFS Traversal. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to create a mirror copy of a tree and display using BFS Traversal.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <stdio.h> #include <stdlib.h> struct btnode { int value; struct btnode *left, *right; }; typedef struct btnode node; /* function prototypes */ void insert(node *, node *); void mirror(node *); /* global variables */ node *root = NULL; int val, front = 0, rear = -1, i; int queue[20]; void main() { node *new = NULL ; int num = 1; printf("Enter the elements of the tree(enter 0 to exit)\n"); while (1) { scanf("%d", &num); if (num == 0) break; new = malloc(sizeof(node)); new->left = new->right = NULL; new->value = num; if (root == NULL) root = new; else { insert(new, root); } } printf("mirror image of tree is\n"); queue[++rear] = root->value; mirror(root); for (i = 0;i <= rear;i++) printf("%d -> ", queue[i]); printf("%d\n", root->right->right->right->value); } /* inserting nodes into the tree */ void insert(node * new , node *root) { if (new->value > root->value) { if (root->right == NULL) root->right = new; else insert (new, root->right); } if (new->value < root->value) { if (root->left == NULL) root->left = new; else insert (new, root->left); } } /* mirror image of nodes */ void mirror(node *root) { val = root->value; if ((front <= rear) && (root->value == queue[front])) { if (root->right != NULL || root->right == NULL) queue[++rear] = root->right->value; if (root->left != NULL) queue[++rear] = root->left->value; front++; } if (root->right != NULL) { mirror(root->right); } if (root->left != NULL) { mirror(root->left); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.