-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exp8_OperationsOnTree.c
111 lines (110 loc) · 2.52 KB
/
Exp8_OperationsOnTree.c
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//Srushti Patil IT-A-43
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer
to left child and a pointer to right child */
struct Node
{
int data;
struct Node *left;
struct Node *right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node *newNode(int data)
{
struct Node *node = (struct Node *) malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
So the tree...
4
/ \
2 5
/ \
1 3
is changed to...
4
/ \
5 2
/ \
3 1
*/
void mirror(struct Node *node)
{
if (node == NULL)
return;
else
{
struct Node *temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
int countnodes(struct Node *root)
{
int count = 0;
if (root != NULL)
{
countnodes(root->left);
count++;
countnodes(root->right);
}
return count;
}
/* Returns a tree which is exact copy of passed tree */
struct Node *cloneBinaryTree(struct Node *root)
{
if (root == NULL)
return NULL;
/* create a copy of root node */
struct Node *NNew = newNode(root->data);
/* Recursively create clone of left and right sub tree */
NNew->left = cloneBinaryTree(root->left);
NNew->right = cloneBinaryTree(root->right);
/* Return root of cloned tree */
return NNew;
}
/* Helper function to print Inorder traversal.*/
void inOrder(struct Node *node)
{
if (node == NULL)
return;
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
/* Driver program to test mirror() */
int main()
{
struct Node *clone;
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
/* Print inorder traversal of the input tree */
printf("Inorder traversal of the constructed tree is \n");
inOrder(root);
/* Convert tree to its mirror */
mirror(root);
/* Print inorder traversal of the mirror tree */
printf("\nInorder traversal of the mirror tree is \n");
inOrder(root);
/*Clone or copy Tree*/
clone=cloneBinaryTree(root);
/*InOrder traversal of clone tree */
printf("\nInorder traversal of the Clone Tree is\n");
inOrder(clone);
printf("\nNumber of nodes in tree = %d", countnodes(root));
return 0;
}