Tree mirror.
Tree mirroring - implementation in c#
The idea is to swap the side left child with the right child in a tree
using System;
class Node
{
public int data;
public Node left;
public Node right;
public Node(int initial_value)
{
data=initial_value;
left=null;
right=null;
}
}
class Tree
{
public Node top;
public Tree()
{
top=null;
}
public Node getTreeNode()
{
return top;
}
public Tree(int initial_value)
{
Node newnode=new Node(initial_value);
top=newnode;
}
public void AddRc(int data)
{
AddR(ref top,data);
}
public void AddR(ref Node N,int data)
{
if(N==null)
{
Node newnode=new Node(data);
N=newnode;
return;
}
if(data>N.data)
{
AddR(ref N.right,data);
return;
}
if(data<N.data)
{
AddR(ref N.left,data);
return;
}
}
public void inorder_traversal(Node N,ref string s)
{
if(N==null)
N=top;
if(N.left!=null)
{
inorder_traversal(N.left,ref s);
s=s+N.data.ToString().PadLeft(3);
}
else
{
s=s+N.data.ToString().PadLeft(3);
}
if(N.right!=null)
{
inorder_traversal(N.right,ref s);
}
}
public void mirror_tree(ref Node node)
{
if(node==null)
return ;
else
{
Node temp;
mirror_tree(ref node.left);
mirror_tree(ref node.right);
temp=node.left;
node.left=node.right;
node.right=temp;
}
}
}
class Program
{
public static void Main()
{
Tree mytree =new Tree();
mytree.AddRc(5);
mytree.AddRc(3);
mytree.AddRc(1);
mytree.AddRc(4);
mytree.AddRc(9);
mytree.AddRc(10);
Node node=mytree.getTreeNode();
string s="";
Console.WriteLine("Inorder Traversal");
mytree.inorder_traversal(null,ref s);
Console.WriteLine(s);
mytree.mirror_tree(ref node);
s=" ";
mytree.inorder_traversal(null,ref s);
Console.WriteLine(s);
}
}
Comments
Post a Comment