Thursday, August 16, 2007

A-Question


Suppose you are trying to print out the mirror image of a tree, a binary tree to boot.
How would you go about doing this? Well, if you know anything about tree structures, you know they are heavily recursive. There are two ways to do this, either modify the tree to be its mirror image, or come up with a way to traverse it mirror-imagedly. The funny thing is, it's virtually the same concept. However, I'm going to show you the former way. (I'll leave it as an exercise to the do latter algorithm)

This is going to be very short and sweet. The only thing you have to do is, change the pointers from right to left, and left to right, assuming you are granted the root node of the tree. Just do it recursively, like so:

void mirrorImage( Node *root )
{
Node *left = root->left;
Node *right = root->right;
root->right = left;
root->left = right;

// now recurse like a heathen
if (left) {
mirrorImage(left);
}
if (right) {
mirrorImage(right);
}
}

So basically you update the pointers, and then do it recursively. After all of this is finished, the result will be the mirror image of the tree.



No comments: