Using System;
Using System.Collections;
Namespace Datastructure
{
<summary>
Summary description of the avltree. -----Balanced Binary Lookup tree
</summary>
public class Avltree:bst
{
The high definition of protected int height;//empty tree is-1;
Construct an empty two-fork lookup tree
Public Avltree (): Base ()
{
//
TODO: Add constructor logic here
//
Height=-1;
}
Public Avltree (Object _obj): Base (_obj)
{
height=0;
}
//------------------------------------------------------------------
protected override Object Getemptyinstance (UINT _degree)
{return new Avltree ();}
//------------------------------------------------------------------
protected int Balancefactor ()
{
if (this. IsEmpty ())
return 0;
Return ((Avltree) this. left). height-((avltree). right). Height;
}
Adjust height
protected void Adjustheight () {This.height=math.max ((avltree) this. left). Height, ((avltree) this. right). height) +1; }
Four ways to rotate when balancing
protected void Llrotation ()
{
if (this. IsEmpty ())
throw new Exception ("My:invalid operation!");
Avltree avlb=new Avltree (This.key);
Avlb.attachsubtree (1, (Avltree) this[0][1]);
Avlb.attachsubtree (2, (Avltree) this[1]);
This.key=this[0]. Key;
THIS[0]=THIS[0][0];
THIS[1]=AVLB;
Adjust the height of two nodes
((Avltree) this. right). Adjustheight ();
This. Adjustheight ();
}
protected void Lrrotation ()
{
if (this. IsEmpty ())
throw new Exception ("My:invalid operation!");
((Avltree) this. left). Rrrotation ();
This. Llrotation ();
}
protected void Rrrotation ()
{
if (this. IsEmpty ())
throw new Exception ("My:invalid operation!");
Avltree avlb=new Avltree (This.key);
Avlb.attachsubtree (1, (Avltree) this[0]);
Avlb.attachsubtree (2, (Avltree) this[1][0]);
Avla.attachsubtree (1,AVLB);
This=avla;
THIS.KEY=THIS[1]. Key;
THIS[0]=AVLB;
THIS[1]=THIS[1][1];
Adjust the height of two nodes
((Avltree) this. left). Adjustheight ();
This. Adjustheight ();
}
protected void Rlrotation ()
{
if (this. IsEmpty ())
throw new Exception ("My:invalid operation!");
((Avltree) this. right). Llrotation ();
This. Rrrotation ();
}//---------------Override--------------------
public override void Attachkey (object _obj)
{
if (! IsEmpty ())
throw new Exception ("My:this node must being a empty tree node!");
This.key=_obj;
Generates a degree-long array and initializes it to an empty tree
This.treelist=new ArrayList ();
this.treelist.capacity= (int) this.degree;
for (int i=0;i<this.degree;i++)
{
Treelist.add (New Avltree ());
}
//
this.height=0;
}
After changing the structure of the tree, balance the tree
public override void Balance ()
{
This. Adjustheight ();
Greater than 1 indicates imbalance
If Math.Abs (this. Balancefactor ()) >1)
{
if (this. Balancefactor () >0)
{if ((Avltree) this. left). Balancefactor () >0)
This. Llrotation ();
Else
This. Lrrotation ();
}
Else
{if ((Avltree) this. right). Balancefactor () <0)
This. Rrrotation ();
Else
This. Rlrotation ();
} } }
public int height{get{return this.height;}}
}