Node.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Btree
{
public class Node
{
public Node leftChild;
public Node rightChild;
public int value;
public Node(int value)
{
leftChild = rightChild = null;
this.value = value;
}
}
}BST.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Btree
{
public class BST
{
private Node root;
public BST()
{
root = null;
}
public void add(int value)
{
root = add(root, value);
}
private Node add(Node root, int value)
{
if (root == null)
root = new Node(value);
else if (root.value > value)
root.leftChild = add(root.leftChild, value);
else
root.rightChild = add(root.rightChild, value);
return root;
}
# region inOrderTraverse
public void inOrderTraverse()
{
inOrderTraverse(root);
Console.ReadLine();
}
private void inOrderTraverse(Node root)
{
if (root == null)
return;
inOrderTraverse(root.leftChild);
Console.WriteLine(root.value);
inOrderTraverse(root.rightChild);
}
#endregion
# region PreorderTraverse
public void PreorderTraverse()
{
PreorderTraverse(root);
Console.ReadLine();
}
private void PreorderTraverse(Node root)
{
if (root == null)
return;
Console.WriteLine(root.value);
PreorderTraverse(root.leftChild);
PreorderTraverse(root.rightChild);
}
# endregion
# region PostorderTraversal
public void PostorderTraversal()
{
PostorderTraversal(root);
Console.ReadLine();
}
private void PostorderTraversal(Node root)
{
if (root == null)
return;
PostorderTraversal(root.leftChild);
PostorderTraversal(root.rightChild);
Console.WriteLine(root.value);
}
# endregionProgram.cs
static void Main(string[] args)
{
BST objbst = new BST();
objbst.add(50);
objbst.add(12);
objbst.add(15);
objbst.add(9);
objbst.add(27);
objbst.add(03);
objbst.add(56);
objbst.add(32);
objbst.PreorderTraverse();
// objbst.inOrderTraverse();
// objbst.PreorderTraverse();
}