我正在尝试实现一个AVL树,但是当我将树打印出来时,它什么也没做。我认为我的左右旋转实现有问题。
我已将两个变量“old”和“new”之间的旋转值转移到了更容易的位置。
private void rotateLeft(ref Node<T> tree)
{
if (tree.Right.BalanceFactor > 0)
{
rotateRight(ref tree.Right);
}
Node<T> oldRoot = tree;
Node<T> newRoot = tree;
newRoot.Right = oldRoot;
oldRoot.Left = newRoot;
newRoot.Right = oldRoot.Left;
}
private void rotateRight(ref Node<T> tree)
{
if (tree.Left.BalanceFactor < 0)
{
rotateLeft(ref tree.Left);
}
Node<T> oldRoot = tree;
Node<T> newRoot = tree;
newRoot.Left = oldRoot;
oldRoot.Right = newRoot;
newRoot.Left = oldRoot.Right;
}
继承节点BalanceFactor
class Node<T> where T : IComparable
{
private T data;
private int balanceFactor = 0; //added for AVLTree
public Node<T> Left, Right;
public int BalanceFactor
{
set { balanceFactor = value; }
get { return balanceFactor; }
}
插入项目
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);
}
答案 0 :(得分:1)
看看这段代码:
Node<T> oldRoot = tree;
Node<T> newRoot = tree;
newRoot.Right = oldRoot;
oldRoot.Left = newRoot;
newRoot.Right = oldRoot.Left;
并尽可能填充tree
。 ......这就是:
tree.Right = tree;
tree.Left = tree;
tree.Right = tree.Left;
我相当确定这不是你想要做的。请查看wikipedia处的AVL平衡算法。