Tree Class
--------------------------------------------------------------------------------------------------------------------------------------
using System;
namespace Tree_Adt_Array_Implementation
{
class BinaryTree
{
private int [] tree;
private int size;
public BinaryTree(int size)
{
this.size = size;
tree = new int[size + 1];
}
public void CreateBinaryTree()
{
for (int i = 1; i <= size; i++)
{
Console.Write("Enter an integer : ");
tree[i] = int.Parse(Console.ReadLine());
}
}
public int searchIndex(int value)
{
int i = 1;
while (i <= size)
{
if (value == tree[i])
return i;
i++;
}
return 0;
}
public int parent(int value)
{
int index;
index = searchIndex(value);
if (index == 0)
{
Console.WriteLine("Node does not exist.");
return 0;
}
else
return tree[index / 2];
}
public int leftchild(int value)
{
int index;
index = searchIndex(value);
if (index == 0)
{
Console.WriteLine("Node does not exist.");
return 0;
}
else
return tree[index * 2];
}
public int rightchild(int value)
{
int index;
index = searchIndex(value);
if (index == 0)
{
Console.WriteLine("Node does not exist.");
return 0;
}
else
return tree[index * 2 + 1];
}
}
}
Driver Program Using Tree ADT
----------------------------------------------------------------------------------------------------------------------------------------------------
using System;
namespace Tree_Adt_Array_Implementation
{
class Program
{
static void Main(string[] args)
{
BinaryTree bt = new BinaryTree(7);
bt.CreateBinaryTree(); //input: {20, 7, 25, 10, 15, 30, 22}
Console.WriteLine("Left child of node 7 {0}",bt.leftchild(7)); //node 10
Console.WriteLine("Right child of node 7 {0}", bt.rightchild(7)); //node 15
Console.WriteLine("Parent of node 7 {0}", bt.parent(20)); // 20
Console.ReadKey();
}
}
}
No comments:
Post a Comment