I'm creating a software product which is an AVLTree containing the details of Authors. The Author class contains: Name, Year Of Publish and List of Books (using LinkedList<> collection). The Author objects will be stored in the AVLTree with the Name as the key for comparison.
My problem is that I can't seem to store the Author class correctly in the AVLTree.
I appreciate any advice and help.
I create the Author array, and create an AVLTree:
public Author[] author = new Author[i];
public AVLTree<Author> authorAVL = new AVLTree<Author>();
The code for the 'Add Author' button is as follows:
author[i].Name = textBoxAddAuthor.Text;
author[i].YrOfPub = textBoxYrOfPub.Text;
author[i] = new Author(author[i].Name, author[i].YrOfPub);
Array.Sort(author);
authorAVL.InsertItem(artist[i]);
I've implemented CompareTo in the Author class as follows:
public int CompareTo(object obj)
{
if (obj is Author) //compare by name
{
Author other = (Author)obj;
return name.CompareTo(other.name);
}
The InsertItem method in the AVLTree looks like this:
public void InsertItem(T item)
{
insertItem(item, ref root);
}
private void insertItem(T item, ref Node<T> tree)
{
if (tree == null)
tree = new Node<T>(item);
else if (item.CompareTo(tree.Data) < 0)
insertItem(item, ref tree.Left);
else if (item.CompareTo(tree.Data) > 0)
insertItem(item, ref tree.Right);
tree.BalanceFactor = (height(tree.Left) - height(tree.Right));
if (tree.BalanceFactor <= -2)
rotateLeft(ref tree);
if (tree.BalanceFactor >= 2)
rotateRight(ref tree);
}
And the node class includes this:
public class Node<T> where T : IComparable
{
private T data;
public Node<T> Left, Right;
private int balanceFactor = 0;
public Node(T item)
{
data = item;
Left = null;
Right = null;
}
public T Data
{
set { data = value; }
get { return data; }
}
public int BalanceFactor
{
set { balanceFactor = value; }
get { return balanceFactor; }
}
}