{
public class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data+" ");
}
}
public class BinarySearchTree
{
public Node root;
public BinarySearchTree()
{
root = null;
}
public void Insert(int i)
{
Node newNode = new Node();
newNode.Data = i;
if (root == null)
{
root = newNode;
}
else
{
Node Current = root;
Node Parent;
while (true)
{
Parent = Current;
if (i < Parent.Data)
{
Current = Current.Left;
if (Current == null)
{
Parent.Left = newNode;
break;
}
}
else
{
Current = Current.Right;
if (Current == null)
{
Parent.Right = newNode;
break;
}
}
}
}
}
public void InOrder(Node theRoot)
{
if (theRoot != null)
{
InOrder(theRoot.Left);
theRoot.DisplayNode();
InOrder(theRoot.Right);
}
}
public void PreOrder(Node theRoot)
{
if (theRoot != null)
{
theRoot.DisplayNode();
PreOrder(theRoot.Left);
PreOrder(theRoot.Right);
}
}
public void PostOrder(Node theRoot)
{
if (theRoot != null)
{
PostOrder(theRoot.Left);
PostOrder(theRoot.Right);
theRoot.DisplayNode();
}
}
}
class Program
{
static void Main(string[] args)
{
BinarySearchTree BST = new BinarySearchTree();
BST.Insert(23);
BST.Insert(45);
BST.Insert(16);
BST.Insert(37);
BST.Insert(3);
BST.Insert(99);
BST.Insert(22);
Console.WriteLine("traversing with InOrder...");
BST.InOrder(BST.root);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("traversing with PreOrder...");
BST.PreOrder(BST.root);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("traversing with PostOrder...");
BST.PostOrder(BST.root);
Console.WriteLine();
Console.WriteLine();
}
}
}


No comments:
Post a Comment