Solution #1: A mirror image of a tree is a tree in which left and right children of each node get swapped. This problem has a recursive nature and therefore can be easily solved with recursion. The algorithm will look like this,
- check if the node is NULL, if yes then return, continue otherwise
- swap left and right child
- repeat for left and right child
Here is the code,
- check if the node is NULL, if yes then return, continue otherwise
- swap left and right child
- repeat for left and right child
Here is the code,
void mirror(node *root) { if(root == NULL) return; //swap left and right children node* temp = root->left; root->left = root->right; root->right = temp; //recursively call on left and right child mirror(root->left); mirror(root->right); }
No comments:
Post a Comment