源代码namespace AVLTree
{
public class Node
{
public int Value;
public Node Left;
public Node Right;
public int Factor;
}
public class AVLTree
{
private Node root;
private Node ParentNode(int x)
{
Node node = root;
Node parent = null;
while (node != null)
{
if (node.Value == x)
{
return parent;
}
parent = node;
if (node.Value > x)
{
node = node.Left;
}
else
{
node = node.Right;
}
}
throw new Exception(string.Format("{0} has no parent", x));
}
public void Insert(int x)
{
Insert(ref root,x);
}
private void Insert(ref Node tree, int x)
{
Node node = new Node() { Value = x };
if (tree == null)
{
tree = node;
}
if (tree.Value > x)
{
Insert(ref tree.Left,x);
if (Depth(tree.Left) - Depth(tree.Right) == 2)
{
if (tree.Left.Value > x)
{
R_Rotate(tree);
}
else if (tree.Left.Value < x)
{
LR_Rotate(tree);
}
}
}
else if (tree.Value < x)
{
Insert(ref tree.Right,x);
if (Depth(tree.Right) - Depth(tree.Left) == 2)
{
if (tree.Right.Value < x)
{
L_Rotate(tree);
}
else if (tree.Right.Value > x)
{
RL_Rotate(tree);
}
}
}
}
public void L_Rotate(Node tree)
{
Node parent = ParentNode(tree.Value);
Node lr = tree.Right;
tree.Right = lr.Left;
lr.Left = tree;
if (parent != null)
{
if (Object.ReferenceEquals(parent.Left, tree))
{
parent.Left = lr;
}
else if (Object.ReferenceEquals(parent.Right, tree))
{
parent.Right = lr;
}
}
else
{
root = tree;
}
}
public void R_Rotate( Node tree)
{
Node parent = ParentNode(tree.Value);
Node lc = tree.Left;
tree.Left = lc.Right;
lc.Right = tree;
if (parent != null)
{
if (Object.ReferenceEquals(parent.Left, tree))
{
parent.Left = lc;
}
else if (Object.ReferenceEquals(parent.Right, tree))
{
parent.Right = lc;
}
}
else
{
root = lc;
}
}
public void LR_Rotate(Node tree)
{
L_Rotate(tree.Left);
R_Rotate(tree);
}
public void RL_Rotate(Node tree)
{
R_Rotate(tree.Right);
L_Rotate(tree);
}
private int Depth(Node tree)
{
if (tree == null) return 0;
else
{
int dleft = Depth(tree.Left);
int dright = Depth(tree.Right);
return (dleft > dright ? dleft + 1 : dright + 1);
}
}
public override string ToString()
{
return Tree(root);
}
private string Tree(Node node)
{
if (node == null)
{
return string.Empty;
}
string left = Tree(node.Left);
string right = Tree(node.Right);
if (!string.IsNullOrEmpty(left) || !string.IsNullOrEmpty(right))
{
return string.Format("{0}({1},{2})", node.Value, Tree(node.Left), Tree(node.Right));
}
else
{
return node.Value.ToString();
}
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
}
}