-2

我正在创建一个软件产品,它是一个包含作者详细信息的 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; }
    }


}
4

1 回答 1

1

在我看来问题出在这里:

author[i].Name = textBoxAddAuthor.Text;
author[i].YrOfPub = textBoxYrOfPub.Text;
author[i] = new Author("Name", "yearofpublish");

特别是操作顺序不对。您正在尝试设置 .. 的属性,author[i]然后用Author.. 的新实例覆盖它没有任何意义。

它应该是:

author[i] = new Author(textBoxAddAuthor.Text, textBoxYrOfPub.Text);

我对代码中的其他三件事也有点困惑:

  1. 如果您首先将它们放在树中,为什么还要有一个包含 Authors 的数组?
  2. 为什么要像这样初始化 autors 数组:public Author[] author = new Author[i];. 从哪里来i
  3. 为什么每次要插入树时都要对数组进行排序?树是自平衡的。。

i然后你在插入树之前重新使用初始化/设置作者..?!

对我来说,以下块:

// where does this i come from here?
author[i].Name = textBoxAddAuthor.Text;                       // this is useless..
author[i].YrOfPub = textBoxYrOfPub.Text;                      // this is useless..
author[i] = new Author(author[i].Name, author[i].YrOfPub);    // overwriting author[i] here
Array.Sort(author);            // why are you sorting the array each time you insert?
authorAVL.InsertItem(artist[i]);

应改写为:

Author newAuthor = new Author(textBoxAddAuthor.Text, textBoxYrOfPub.Text);
authorAVL.InsertItem(newAuthor);
于 2013-03-15T15:30:13.067 回答