some algorithmic puzzles, tutorials, interview questions... and stuff...

Friday, September 04, 2009

How to mirror a binary tree

Easy, but you have to be prepared for anything :) Mirroring means switching the pointers around, inside of the tree, so that the resulting tree looks like it's mirror copy of the original tree. Here's an example.
So the tree:

   1:             10
   2:            /   \
   3:           7     25
   4:         /   \
   5:        2     8
becomes:

   1:             10
   2:            /   \
   3:           25    7
   4:               /   \
   5:              8     2
The solution has to be O(n) because it has to change all the pointers from all the nodes, so it can't be done faster.

   1:  void mirror(struct node* head) {
   2:      if (head == 0)
   3:          return;
   4:      node* temp = head->left;
   5:      head->left = head->right;
   6:      head->right = temp; // switch left child with right child
   7:      mirror(head->left); // then repeat the process with each child
   8:      mirror(head->right);
   9:  }
This can be easily expanded for generic trees with more than two children, the basic idea remains the same.

No comments:

Post a Comment