Thursday, 2 August 2012

C program to create a mirror copy of a tree (left nodes become right nodes and right nodes become left nodes as well)


//The structure for the following code

typedef struct tree
{
int value;
struct tree *left,*right;                           //known as self-referential pointers
} mynode;



//The following C code will create a new mirror copy tree.

mynode *copy(mynode *root)
{
mynode *temp;

if(root==NULL)return(NULL);

temp = (mynode *) malloc(sizeof(mynode));
temp->value = root->value;

temp->left = copy(root->right);
temp->right = copy(root->left);

return(temp);
}


//The following C code will only print the mirror of the tree

void tree_mirror(mynode *node) 

mynode *temp;

if (node==NULL) 

return; 

else 

tree_mirror(node->left); 
tree_mirror(node->right); 

// Swap the pointers in this node 
temp = node->left; 
node->left = node->right; 
node->right = temp; 

}


//after execution of above method, print the tree

No comments:

Post a Comment