At the moment I am learning algorithms and here I am trying to implement a simple binary search tree. I would like to know your suggestions on whether I am on the right track or not, and how this can be improved.
BinaryTree.cs
class BinaryTree
{
private Node root;
private int count;
public BinaryTree()
{
root = null;
count = 0;
}
public bool isEmpty()
{
return root == null;
}
public void insert(int d)
{
if (isEmpty())
{
root = new Node(d);
}
else
{
root.insertData(ref root, d);
}
count++;
}
public bool search(int s)
{
return root.search(root, s);
}
public bool isLeaf()
{
if(!isEmpty())
return root.isLeaf(ref root);
return true;
}
public void display()
{
if(!isEmpty())
root.display(root);
}
public int Count()
{
return count;
}
}
Node.cs
class Node
{
private int number;
public Node rightLeaf;
public Node leftLeaf;
public Node(int value)
{
number = value;
rightLeaf = null;
leftLeaf = null;
}
public bool isLeaf(ref Node node)
{
return (node.rightLeaf == null && node.leftLeaf == null);
}
public void insertData(ref Node node, int data)
{
if (node == null)
{
node = new Node(data);
}
else if (node.number < data)
{
insertData(ref node.rightLeaf, data);
}
else if (node.number > data)
{
insertData(ref node.leftLeaf, data);
}
}
public bool search(Node node, int s)
{
if (node == null)
return false;
if (node.number == s)
{
return true;
}
else if (node.number < s)
{
return search(node.rightLeaf, s);
}
else if (node.number > s)
{
return search(node.leftLeaf, s);
}
return false;
}
public void display(Node n)
{
if (n == null)
return;
display(n.leftLeaf);
Console.Write(" " + n.number);
display(n.rightLeaf);
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
BinaryTree b = new BinaryTree();
b.insert(1);
b.insert(6);
b.insert(2);
b.insert(4);
b.insert(5);
b.insert(3);
b.display();
Console.ReadLine();
}
}
Output
1 2 3 4 5 6