Amazon Interview Question

Write a function to mirror a binary tree (left node to right, right to left, etc). How about very unbalance tree?

Interview Answers

Anonymous

Sep 7, 2011

This can be done with a recursive function that traverses the tree using post order depth traversal. Once the recursive calls to the left and right subtrees return, swap the left and right pointers. The base case would be when the pointer is null. The balance of the tree doesn't matter for this algorithm.

3

Anonymous

Sep 12, 2011

The function is as simple as: void mirror_node(node* n) { if (n) { node* tmp = n->left; n->left = n->right; n->right = tmp; mirror_node(n->left); mirror_node(n->right); } }

3