Shutterfly Interview Question
Software Engineer / DevelopersCountry: United States
To make this thread-safe, we can simply make the function synchronized, right? Here's my solution:
public synchronized void mirror(Node root) {
if (root == null) {
return;
} else {
mirror(root.left);
mirror(root.right);
Node temp = root.right;
root.right = root.left;
root.left = temp;
}
}
Now, it is possible to split the tree into sub-trees to improve thread-safety but this is simple and should just work.
To get around using a temp variable in your mirror function you can pass a variable by ref. Here is a sample that might work
void mirrorTree(tree_node * root, tree_node ** n)
{
if(!root)
{
*n = NULL;
return;
}
*n = new tree_node;
(*n)->data = root->data;
mirrorTree(root->left,&(*n)->left);
mirrorTree(root->right, &(*n)->right);
}
- tazo August 08, 2012