Popular Posts

Thursday, July 28, 2011

Mirror image of a tree in iterative way

Algorithm : push all nodes of a binary tree into a stack.Pop element by element from the stack and exchange left and right pointers of the popped node.

void mirror(node* root)
{
        if(root == NULL) return;
        node *temp;
        node *q[100] = {NULL};
        int i,j;
        i = j = 0;
       
        while(root)
        {
                temp = root->left;
                root->left = root->right;
                root->right = temp;
                //printf("%d %d",root->left->data,root->right->data);
                if(root->left)
                        q[i++] = root->left;
                if(root->right)
                        q[i++] = root->right;
                root = q[j++];
        }
}
Refer for complete code : http://www.ideone.com/NyAmw

No comments:

Post a Comment