Mirror of a binary tree


This is continuation of my post How to create binary tree in c#.In this post I will show you how convert a given binary tree into it’s mirror image.

/**

Changes the tree into its mirror image.

So the tree…

4

/ \

2 5

/ \

1 3

is changed to…

4

/ \

5 2

/ \

3 1

Strategy: Uses a recursive helper that recurs over the tree, swapping the left/right pointers.

public void MirrorTree()
        {
            MirrorTree(_root);
        }

private void MirrorTree(Node node)
        {
            if (node != null)
            {
                // do the sub-trees 
                MirrorTree(node.Left);
                MirrorTree(node.Right);

                // swap the left/right pointers 
                Node temp = node.Left;
                node.Left = node.Right;
                node.Right = temp;
            }
 }

Happy Coding 😊


Reactions

Post a Comment

0 Comments

Close Menu