AVL樹旋轉圖解
来源:互联网 发布:正规的淘宝代运营 编辑:程序博客网 时间:2024/06/05 03:51
AVL樹是一顆平衡樹,其左右子樹的高度差不會超過一層。爲了保持這一性質,採用旋轉節點的方式來降低高度。
如下圖,紅色表示新插入的節點,一共4种情況:
- 左左:節點1插入到左子樹的左節點,導致節點5不平衡。
實際上我們只需要關心節點1、3、5,根據二叉搜索樹的性質(左 < 中 < 右),所以祇有節點3才可以作為父節點,於是將節點5繞節點3進行一次左旋,達到平衡。
- 右右:和左左類似,可以通過一次右旋來實現平衡,如下圖:
- 左右:這种情況光旋轉失衡的節點5是不夠的,因爲節點3是無法成爲父節點的,祇有節點4才有可能。
所以先把節點3右旋以使節點4居中,再將節點5左旋,共兩次旋轉實現平衡。
- 右左:和左右的情況類似,也是兩次,先左旋后右旋。
class AVLNode<T> { public T Value { get; set; } public AVLNode<T> Left { get; set; } public AVLNode<T> Right { get; set; } public int Height { get { return Math.Max(GetHeight(Left), GetHeight(Right)) + 1; } } public static int GetHeight(AVLNode<T> node) { return (node == null) ? -1 : node.Height; } } class AVLTree<T> where T : IComparable<T> { public AVLNode<T> Root { get; set; } public void Insert(T value) { Root = Insert(value, Root); } private AVLNode<T> Insert(T value, AVLNode<T> node) { if (node == null) return new AVLNode<T> { Value = value }; int result = value.CompareTo(node.Value); if (result < 0) { node.Left = Insert(value, node.Left); if (AVLNode<T>.GetHeight(node.Left) - AVLNode<T>.GetHeight(node.Right) == 2) { if (value.CompareTo(node.Left.Value) < 0) { node = RotateLeft(node); } else { node = RotateRightLeft(node); } } } else if (result > 0) { node.Right = Insert(value, node.Right); if (AVLNode<T>.GetHeight(node.Right) - AVLNode<T>.GetHeight(node.Left) == 2) { if (value.CompareTo(node.Right.Value) > 0) { node = RotateRight(node); } else { node = RotateLeftRight(node); } } } else { } return node; } private AVLNode<T> RotateLeft(AVLNode<T> node) { var child = node.Left; node.Left = child.Right; child.Right = node; return child; } private AVLNode<T> RotateRight(AVLNode<T> node) { var child = node.Right; node.Right = child.Left; child.Left = node; return child; } private AVLNode<T> RotateRightLeft(AVLNode<T> node) { node.Left = RotateRight(node.Left); return RotateLeft(node); } private AVLNode<T> RotateLeftRight(AVLNode<T> node) { node.Right = RotateLeft(node.Right); return RotateRight(node); } }
有了圖,代碼就不難理解了
<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
- AVL樹旋轉圖解
- avl
- avl
- {avl}
- AVL
- AVL
- AVL
- AVL
- AVL
- AVL
- AVL
- AVL
- HDU2193-AVL-数据结构-AVL
- AVL代码
- AVL Tree
- AVL树
- AVL树
- AVL树
- C++学习笔记(二)
- jar使用
- 在线学习编程网站收集
- JFileChooser文件类型筛选
- 在Ubuntu上为Android系统编写Linux内核驱动程序
- AVL樹旋轉圖解
- opencv初识,敬初学者,opencv安装办法
- 这几天有django和python做了一个多用户博客系统(可选择模板) 没完成,先分享下
- Python修炼--常用字符串、数学函数
- mp4播放资料
- 1.窗体与界面设计
- Common Lisp 学习书目
- 编写程序,输入某一时刻的时间,加一秒后输出新的时间,时间以时、分、秒表示(利用结构类型)
- 黑马程序员-------JAVA图文复习八