数据结构与算法(C#实现)系列---AVLTree(一)(转)

本文介绍了使用C#实现AVL树的过程,包括基本概念、关键操作如插入、删除及旋转等,并详细解释了如何通过调整高度保持树的平衡。

数据结构与算法(C#实现)系列---AVLTree(一)

using System;

using System.Collections;

namespace DataStructure

{

///

/// AVLTree 的摘要说明。-----平衡二叉查找树

///

public class AVLTree:BST

{

protected int height;//空树的高定义为-1;

//构造一棵空的二叉查找树

public AVLTree():base()

{

//

// TODO: 在此处添加构造函数逻辑

//

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)this.Right).height;

}

//调整高度

protected void AdjustHeight(){ this.height=Math.Max( ((AVLTree)this.Left).height, ((AVLTree)this.Right).height)+1; }

//平衡时的四种旋转方式

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;

//调整两个节点的高度

((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];

//调整两个节点的高度

((AVLTree)this.Left).AdjustHeight();

this.AdjustHeight();

}

protected void RLRotation()

{

if( this.IsEmpty() )

throw new Exception("My:invalid operation!");

((AVLTree)this.Right).LLRotation();

this.RRRotation();

}

[@more@]数据结构与算法(C#实现)系列---AVLTree(一)

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8781179/viewspace-924559/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/8781179/viewspace-924559/

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值