我正在创建一个软件产品,它是一个包含作者详细信息的 AVLTree。Author 类包含:姓名、出版年份和图书列表(使用 LinkedList<> 集合)。Author 对象将存储在 AVLTree 中,名称作为比较键。
我的问题是我似乎无法将 Author 类正确存储在 AVLTree 中。
我感谢任何建议和帮助。
我创建了 Author 数组,并创建了一个 AVLTree:
public Author[] author = new Author[i];
public AVLTree<Author> authorAVL = new AVLTree<Author>();
“添加作者”按钮的代码如下:
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]);
我在 Author 类中实现了 CompareTo,如下所示:
public int CompareTo(object obj)
{
if (obj is Author) //compare by name
{
Author other = (Author)obj;
return name.CompareTo(other.name);
}
AVLTree 中的 InsertItem 方法如下所示:
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);
}
节点类包括:
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; }
}
}