|
|
|
|
![]() ![]() |
Oct 26 2007, 08:50 AM
Post
#1
|
|
|
Super Member ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() Group: [HOSTED] Posts: 328 Joined: 1-October 07 From: India Member No.: 50,968 |
Given a binary tree, write an algorithm to find its mirror image with minimal time and space complexities.
Note: If you know the answer and if you feel it is simple also please post the answers so that others will come to know about the answers. This question was sent by my friend through mail. Solutions Suggested Sol 1 CODE void PrintMirror(node *root) { if(node!=NULL) PrintMirror(root->right); Printf(root->data); PrintMirror(root->left); } In case of implementation using array 2i+1 stores left child of ith node and 2i+2 stores right element. CODE for(int i=0;i<(2^levels)-1;i++) { swap(tree[2i+1],tree[2i+2]); } Note: Null nodes are also to be swaped hence (2^levels)-1 -- Suggested by my friend... Sol 2 Another Solution.... CODE void Mirror(node *ptr) { if(ptr!=(node *) NULL) { node* right=ptr->right; Mirror(ptr->left); Mirror(ptr->right); ptr->right=ptr->left; ptr->left=right; } } Time complexity : O(n). Each node is processed once. Space complexity : only one temp ptr used. More solutions welcome... One more Solution here... Sol 3 One more algo CODE node* mirror(node **tree)
{ node * temptree; if(*tree!=(node*)NULL) { temptree =(node*)malloc(sizeof(node)); temptree->left = mirror(tree->right); temptree->data = tree->data; temptree->right = mirror(tree->left); return(temptree); } else printf("Tree is empty !!"); This post has been edited by varalu: Oct 26 2007, 09:52 AM |
|
|
|
![]() ![]() |
Similar Topics
|
Lo-Fi Version | Time is now: 21st November 2008 - 07:24 AM |