Traversing a tree in Inorder reversal
Below is the code for reversing an inorder traversal of a tree
using System;
class node
{
public int data;
public node left;
public node right;
public node(int value_initial)
{
data=value_initial;
left=null;
right=null;
}
}
class tree
{
node top;
int count;
public int element;
public tree()
{
top=null;
count=0;
element=0;
}
public tree(int value_initial)
{
top =new node(value_initial);
}
public void AddR(int value_initial)
{
AddRc(ref top, value_initial);
}
private void AddRc(ref node N, int value_initial)
{
if(N==null)
{
node newnode=new node(value_initial);
N=newnode;
return;
}
if(value_initial < N.data)
{
AddRc(ref N.left,value_initial);
return;
}
if(value_initial >= N.data)
{
AddRc(ref N.right,value_initial);
return;
}
}
public void inorder_traversal(node n,ref string s)
{
if(n==null)
{
n=top;
}
if(n.right!=null)
{
inorder_traversal(n.right,ref s);
s=s+n.data.ToString().PadLeft(3);
}
else
{
s=s+n.data.ToString().PadLeft(3);
}
if(n.left!=null)
{
inorder_traversal(n.left,ref s,k);
}
}
}
class program
{
public static void Main()
{
string result="";
tree newtree=new tree();
newtree.AddR(20);
newtree.AddR(22);
newtree.AddR(8);
newtree.AddR(5);
newtree.AddR(10);
newtree.AddR(9);
newtree.AddR(12);
int k=3;
Console.WriteLine("Reverse Inorder traversal");
newtree.inorder_traversal(null,ref result);
Console.WriteLine(result);
Console.WriteLine("the kth element",newtree.element);
}
}
class node
{
public int data;
public node left;
public node right;
public node(int value_initial)
{
data=value_initial;
left=null;
right=null;
}
}
class tree
{
node top;
int count;
public int element;
public tree()
{
top=null;
count=0;
element=0;
}
public tree(int value_initial)
{
top =new node(value_initial);
}
public void AddR(int value_initial)
{
AddRc(ref top, value_initial);
}
private void AddRc(ref node N, int value_initial)
{
if(N==null)
{
node newnode=new node(value_initial);
N=newnode;
return;
}
if(value_initial < N.data)
{
AddRc(ref N.left,value_initial);
return;
}
if(value_initial >= N.data)
{
AddRc(ref N.right,value_initial);
return;
}
}
public void inorder_traversal(node n,ref string s)
{
if(n==null)
{
n=top;
}
if(n.right!=null)
{
inorder_traversal(n.right,ref s);
s=s+n.data.ToString().PadLeft(3);
}
else
{
s=s+n.data.ToString().PadLeft(3);
}
if(n.left!=null)
{
inorder_traversal(n.left,ref s,k);
}
}
}
class program
{
public static void Main()
{
string result="";
tree newtree=new tree();
newtree.AddR(20);
newtree.AddR(22);
newtree.AddR(8);
newtree.AddR(5);
newtree.AddR(10);
newtree.AddR(9);
newtree.AddR(12);
int k=3;
Console.WriteLine("Reverse Inorder traversal");
newtree.inorder_traversal(null,ref result);
Console.WriteLine(result);
Console.WriteLine("the kth element",newtree.element);
}
}
Comments
Post a Comment