【数据结构】平衡二叉排序树BBST之AVL树

平衡二叉排序树

平衡二叉排序树(Balanced Binary Sort Tree),上一篇博客【数据结构】二叉排序树BST讲了BST,并且在最后我们说BST上的操作不会超过O(h),既然树高这么重要,那么BBST的研究就是为了使得树的深度在可接受的范围内渐近意义下达到O(lgn)

n个节点组成的二叉树,其高度为lgn取下限时,这棵树是理想平衡的,满足这样条件的树只有完全二叉树和满二叉树,这样的要求未免太苛刻,并且实际中没有意义。

适度平衡:保证树高在渐近意义上不超过O(lgn)适度平衡的树也称作平衡二叉树。

并且我们知道,任何平衡的二叉树在经过一系列的插入删除操作后可能会不平衡,因此任何一种BBST都包含了界定平衡的标准和一系列重平衡(rebalance)的方法。

平衡二叉排序树包括:AVL树,红黑树,伸展树等


AVL树

AVL树仅仅是平衡二叉树的一种,它是最经典的最早发明的一种BBST(貌似严蔚敏老师的书上说平衡二叉树又称AVL树),AVL树由G.M. Adelson-Velsky 和 E.M. Landis发明。
AVL定义适度平衡的标准:
定义平衡因子(BalanceFactor):BF(node) = height(lchild(node)) - height(rchild(node))
对所有的节点node,有|BF(node)| <= 1

一系列的重平衡方法:旋转操作

基本的旋转操作如下图所示


根据不同的情形又分为四种情况


相关算法

1.返回某个结点的高度height
我们设定当结点为null时的高度为-1,其余情况的高度由每个结点自己维护。

private int height(BinaryTreeNode node) {
		if (node == null) {
			return -1;
		} else {
			return node.height;
		}
	}

2.返回某个结点的平衡因子
平衡因子等于左子树高度减右子树高度

private int balance(BinaryTreeNode node) {
		if (node == null)
			return 0;
		return height(node.lchild) - height(node.rchild);
	}

3.左旋LL

按照图示顺序分三步,将tmp作为最终的根结点返回。

需要额外做的工作包括对父结点改变了的结点赋新的parent,更新高度,最终返回的结点的父亲节点一定要在调用处设置!!
// LL   将node结点左旋,node是最小不平衡子树的根
public BinaryTreeNode leftRotate(BinaryTreeNode node) {
		BinaryTreeNode tmp = node.lchild;
		tmp.parent = null;
		node.lchild = tmp.rchild;
		if (tmp.rchild != null)
			tmp.rchild.parent = node;
		tmp.rchild = node;
		node.parent = tmp;
		// 更新高度,包括是node和node.rchild
		node.height = Math.max(height(node.lchild),height(node.rchild)) + 1;
		tmp.height = Math.max(height(tmp.lchild),node.height) + 1;
		return tmp;
	}

4.双旋LR
分两步即可,先对结点的左子树进行左旋操作,再对该结点进行右旋操作,要注意保存第一次返回的结点的父亲结点!!

public BinaryTreeNode leftRightRotate(BinaryTreeNode node) {
		node.lchild = rightRotate(node.lchild);
		node.lchild.parent = node; // 父结点赋值!!
		return leftRotate(node);
	}

5.返回待旋转的结点的旋转类型
private RotateType rotateType(BinaryTreeNode node) {
		if (balance(node) < -1) {
			if (balance(node.rchild) > 0) {
				return RotateType.RL;
			} else {
				return RotateType.RR;
			}
		} else { // >1
			if (balance(node.lchild) < 0) {
				return RotateType.LR;
			} else {
				return RotateType.LL;
			}
		}
	}

6.用以node为顶点旋转过后的树来代替node这棵子树

区别之前用的replace函数void replace(BinaryTreeNode node1,BinaryTreeNode node2)

将结点A旋转后,A的父结点左右孩子都已经变了,因此要先将他的父结点保存下来以便将旋转后的子树往它后面挂,所以对该函数的调用不等于调用replace(node,leftRotate(node),type);

// 拼接旋转后的子树:用以node为定点旋转过后的树来代替node这棵子树
	private void replaceNode(BinaryTreeNode node,RotateType type) {
		BinaryTreeNode tmpParent = node.parent;
		BinaryTreeNode rotateNode = null;
		switch (type) {
		case LL:
			rotateNode = leftRotate(node);
			break;
		case RR:
			rotateNode = rightRotate(node);
			break;
		case LR:
			rotateNode = leftRightRotate(node);
			break;
		case RL:
			rotateNode = rightLeftRotate(node);
			break;
		}
		if (tmpParent == null) {
			root = rotateNode;
			rotateNode.parent = null; //父结点赋值非常关键!!
		} else if (tmpParent.rchild == node) {
			tmpParent.rchild = rotateNode;
			rotateNode.parent = root; //父结点赋值非常关键!!
		} else {
			tmpParent.lchild = rotateNode;
			rotateNode.parent = root; //父结点赋值非常关键!!
		}
	}


插入和删除

有了上面一些基本的函数,就可以进行下面的两个重要操作:插入/删除结点

插入节点

当插入一个结点可能会造成他的祖父结点失衡,进而曾祖父结点也会失衡等等一直往上延伸。这么看来插入操作似乎很复杂?事实并不是这样,尽管这样,我们却不需要从下往上挨个调整结点至平衡。因为好消息是只要把从下往上的第一个失衡的结点所构成的子树重平衡就能保证其之上的所有结点平衡。这里的第一个失衡的结点所构成的子树称为最小不平衡子树。调整最小不平衡子树至重平衡,它的高度和插入结点之前相比未变,因此也不会影响到更上层的结点。这样只需要有限步操作即可重平衡,复杂度为O(1)。

这里每插入一个节点都要更新已存在的结点的高度!插入的实现和BST里面一样,只是要更新结点高度

private BinaryTreeNode insertRecurAVL(BinaryTreeNode root,BinaryTreeNode insertNode) {
		if (this.root == null) {
			this.root = root = insertNode;
		} else if (insertNode.data < root.data && root.lchild == null) {
			root.lchild = insertNode;
			insertNode.parent = root;
		} else if (insertNode.data >= root.data && root.rchild == null) {
			root.rchild = insertNode;
			insertNode.parent = root;
		} else {
			if (insertNode.data < root.data && root.lchild != null)
				insertRecurAVL(root.lchild,insertNode);
			if (insertNode.data >= root.data && root.rchild != null)
				insertRecurAVL(root.rchild,insertNode);
		}
		// 更新高度!
		root.height = Math.max(height(root.lchild),height(root.rchild)) + 1;// 放在这里的位置很重要
		return insertNode;
	}
于是插入节点后对其进行检查重平衡的代码如下,基本思路是将新的结点插入到对应的位置,然后从他开始往上走,直到遇到第一个不平衡的结点,也就是最小不平衡子树,
然后旋转这个结点让其恢复平衡后来替换该结点。

public void insertAVL(BinaryTreeNode insertNode) {
		BinaryTreeNode node = insertRecurAVL(root,insertNode);

		// 调整最小不平衡子树
		while (node != null && balance(node) > -2 && balance(node) < 2) {
			node = node.parent;
		} // 跳出循环时,node为null 或者node不平衡
		if (node != null) {
			// 确定何种类型的旋转
			RotateType type = rotateType(node);
			replaceNode(node,type);
		}
	}
从数组创建一棵BBST的过程也可以通过insert操作循环的插入即可。

删除结点

删除某个节点只可能导致他的父亲节点失衡,因为,如果我们删除最深的那条子树,那么不会失衡,所以产生失衡只可能是由于删除了短的子树上的结点,这样对外界来说,该结点的父亲所在的子树的高度未变,于是上面的结点的平衡性也不会改变。那么删除操作只需要重平衡它的父结点吗?事实上,删除一个结点他的父亲如果发生了失衡,那么当让其父亲节点重平衡后,局部子树的高度减少了,因此失衡的情况可能继续往上传递,最差情况下一直传递到根,于是删除的复杂度为O(lgn)。其实也就是因为这个原因,AVL树用的不多,SGI的STL中都未实AVL树,仅仅实现了红黑树

// 删除AVL树中的结点
public void deleteAVL(BinaryTreeNode node) {
		System.out.println(node.toString());
		BinaryTreeNode predecessorOfnode = null;
        if (node.lchild == null) { // 左子树为空,只需要移植右子树  
            replace(node,node.rchild);  
        } else if (node.rchild == null) {  
            replace(node,node.lchild);  
        } else {   
            predecessorOfnode = predecessor(node);  
            replace(node,node.lchild);  
            predecessorOfnode.rchild = node.rchild;  
            node.rchild.parent = predecessorOfnode;
            predecessorOfnode.height = Math.max(height(predecessorOfnode.lchild),height(node.rchild)) + 1;
        }
		// 调整平衡
		// 只需要从删除的结点的前驱开始依次向上判断
		BinaryTreeNode nodetmp = predecessorOfnode;
		while (nodetmp != null) {
			BinaryTreeNode tmp = nodetmp.parent; // 下面的旋转操作会改变nodetmp的父结点,所以提前保存下来!!
			if (balance(nodetmp) < -1 || balance(nodetmp) > 1) {
				// 不平衡
				RotateType type = rotateType(nodetmp);
				replaceNode(nodetmp,type);
			} 
			nodetmp = tmp;
		}
	}


AVL树的实现

其中使用的BinaryTreeNode比起之前多了一个height字段,用来保存每个节点的高度,结点为null时,高度为-1

public class AVLTree extends BinarySearchTree {
	public enum RotateType {
		LL,RR,LR,RL
	};

	@Override
	public void createTree(int[] array) {
		// 从一个数组创建二叉搜索树
		for (int i : array) {
			insertAVL(new BinaryTreeNode(i));
		}
	}

	// 删除AVL树中的结点
	public void deleteAVL(BinaryTreeNode node) {
		BinaryTreeNode predecessorOfnode = null;
		if (node.lchild == null) { // 左子树为空,只需要移植右子树
			replace(node,node.rchild);
		} else if (node.rchild == null) {
			replace(node,node.lchild);
		} else {
			predecessorOfnode = predecessor(node);
			replace(node,node.lchild);
			predecessorOfnode.rchild = node.rchild;
			node.rchild.parent = predecessorOfnode;
			predecessorOfnode.height = Math.max(
					height(predecessorOfnode.lchild),height(node.rchild)) + 1;
		}
		// 调整平衡
		// 只需要从删除的结点的前驱开始依次向上判断
		BinaryTreeNode nodetmp = predecessorOfnode;
		while (nodetmp != null) {
			BinaryTreeNode tmp = nodetmp.parent; // 下面的旋转操作会改变nodetmp的父结点,所以提前保存下来!!
			if (balance(nodetmp) < -1 || balance(nodetmp) > 1) {
				// 不平衡
				RotateType type = rotateType(nodetmp);
				replaceNode(nodetmp,type);
			}
			nodetmp = tmp;
		}
	}

	// 插入节点 并处理可能的不平衡结点
	public void insertAVL(BinaryTreeNode insertNode) {
		BinaryTreeNode node = insertRecurAVL(root,insertNode);
		while (node != null && balance(node) > -2 && balance(node) < 2) {
			node = node.parent;
		} // 跳出循环时,node为null 或者node不平衡
		if (node != null) {
			// 确定何种类型的旋转
			RotateType type = rotateType(node);
			replaceNode(node,type);
		}
	}

	// 递归的插入结点,同时更新每个结点的高度
	private BinaryTreeNode insertRecurAVL(BinaryTreeNode root,insertNode);
		}
		root.height = Math.max(height(root.lchild),height(root.rchild)) + 1;// 放在这里的位置很重要
		return insertNode;
	}

	// 拼接旋转后的子树:用以node为定点旋转过后的树来代替node这棵子树
	private void replaceNode(BinaryTreeNode node,RotateType type) {
		BinaryTreeNode tmpParent = node.parent;
		BinaryTreeNode rotateNode = null;
		switch (type) {
		case LL:
			rotateNode = leftRotate(node);
			break;
		case RR:
			rotateNode = rightRotate(node);
			break;
		case LR:
			rotateNode = leftRightRotate(node);
			break;
		case RL:
			rotateNode = rightLeftRotate(node);
			break;
		}
		if (tmpParent == null) {
			root = rotateNode;
			rotateNode.parent = null; // 父结点赋值非常关键!!
		} else if (tmpParent.rchild == node) {
			tmpParent.rchild = rotateNode;
			rotateNode.parent = root; // 父结点赋值非常关键!!
		} else {
			tmpParent.lchild = rotateNode;
			rotateNode.parent = root; // 父结点赋值非常关键!!
		}
	}

	// 获取待旋转结点的旋转类型
	private RotateType rotateType(BinaryTreeNode node) {
		if (balance(node) < -1) {
			if (balance(node.rchild) > 0) {
				return RotateType.RL;
			} else {
				return RotateType.RR;
			}
		} else { // >1
			if (balance(node.lchild) < 0) {
				return RotateType.LR;
			} else {
				return RotateType.LL;
			}
		}
	}

	// 返回结点的平衡因子 返回值为-2 -1 0 1 2
	private int balance(BinaryTreeNode node) {
		if (node == null)
			return 0;
		return height(node.lchild) - height(node.rchild);
	}

	// 返货某个节点的高度
	private int height(BinaryTreeNode node) {
		if (node == null) {
			return -1;
		} else {
			return node.height;
		}
	}

	// 将node结点左旋,node是最小不平衡子树的根
	// RR
	public BinaryTreeNode rightRotate(BinaryTreeNode node) {
		BinaryTreeNode tmp = node.rchild;
		tmp.parent = null;
		node.rchild = tmp.lchild;
		if (tmp.lchild != null)
			tmp.lchild.parent = node;
		tmp.lchild = node;
		node.parent = tmp;
		// 更新高度,包括是node和node.rchild
		node.height = Math.max(height(node.lchild),height(node.rchild)) + 1;
		tmp.height = Math.max(height(tmp.rchild),node.height) + 1;
		return tmp;
	}

	// 将node结点左旋,node是最小不平衡子树的根
	// LL
	public BinaryTreeNode leftRotate(BinaryTreeNode node) {
		BinaryTreeNode tmp = node.lchild;
		tmp.parent = null;
		node.lchild = tmp.rchild;
		if (tmp.rchild != null)
			tmp.rchild.parent = node;
		tmp.rchild = node;
		node.parent = tmp;
		// 更新高度,包括是node和node.rchild
		node.height = Math.max(height(node.lchild),node.height) + 1;
		return tmp;
	}

	// LR
	public BinaryTreeNode leftRightRotate(BinaryTreeNode node) {
		node.lchild = rightRotate(node.lchild);
		node.lchild.parent = node;
		return leftRotate(node);
	}

	// RL
	public BinaryTreeNode rightLeftRotate(BinaryTreeNode node) {
		node.rchild = leftRotate(node.rchild);
		node.rchild.parent = node;
		return rightRotate(node);
	}

}

测试

仍然使用上篇博客中创建BST的数组int[] array = { 1,9,2,7,4,5,3,6,8 };

public static void main(String[] args) {
		AVLTree avl = new AVLTree();
		int[] array = { 1,8 };
		avl.createTree(array);
		System.out.println("层序打印结点和其高度");
		avl.levelOrderH();
		System.out.println("删除结点7得到的层序遍历");
		avl.deleteAVL(avl.search(avl.root,7));
		avl.levelOrderH();
	}

输出

层序打印结点和其高度
4  
2  7  
1  3  5  9  
6  8  

删除结点7得到的层序遍历
4  
2  8  
1  3  5  9  
6 
可以发现,前面将该数组创建成BST,树高非常高,现在将其创建成AVL树,发现非常的平衡,树高比之前低多了。并且在动态插入和删除过程中始终能维护树的平衡性。

分析

分析该数组的创建和删除结点的过程

上述的代码在通过该数组创建AVL树的过程如下


删除结点7的过程如下图



后记

可能最后的代码才200行左右,但是编些难度不小,比起写个应用分分钟上千行代码难多了,改bug改了一个晚上。由于我在这里每个节点保存父结点,所以好几次忘记给父结点赋值,旋转的时候,由于指针变化也会产生好多问题,编写代码的过程中遇到导致错误的地方都标注在代码中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


【啊哈!算法】算法3:最常用的排序——快速排序       上一节的冒泡排序可以说是我们学习第一个真正的排序算法,并且解决了桶排序浪费空间的问题,但在算法的执行效率上却牺牲了很多,它的时间复杂度达到了O(N2)。假如我们的计算机每秒钟可以运行10亿次,那么对1亿个数进行排序,桶排序则只需要0.1秒,而冒泡排序则需要1千万秒,达到115天之久,是不是很吓人。那有没有既不浪费空间又可以快一点的排序算法
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正则表达式就可以组成第一个构造。正如稍后要介绍的一样,既然也可以命名组,大家就有考虑把这个构造作为匿名组。作为一个实例,请看看下列字符串: “08/14/57 46 02/25/59 45 06/05/85 18 03/12/88 16 09/09/90 13“ 这个字符串就是由生日和年龄组成的。如果需要匹配年两而不要生日,就可以把正则
选择排序:从数组的起始位置处开始,把第一个元素与数组中其他元素进行比较。然后,将最小的元素方式在第0个位置上,接着再从第1个位置开始再次进行排序操作。这种操作一直到除最后一个元素外的每一个元素都作为新循环的起始点操作过后才终止。 public void SelectionSort() { int min, temp;
public struct Pqitem { public int priority; public string name; } class CQueue { private ArrayList pqueue; public CQueue() { pqueue
在编写正则表达式的时候,经常会向要向正则表达式添加数量型数据,诸如”精确匹配两次”或者”匹配一次或多次”。利用数量词就可以把这些数据添加到正则表达式里面了。 数量词(+):这个数量词说明正则表达式应该匹配一个或多个紧紧接其前的字符。 string[] words = new string[] { "bad", "boy", "baad", "baaad" ,"bear", "b
来自:http://blog.csdn.net/morewindows/article/details/6678165/归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。首先考虑下如何将将二个有序数列合并。这个非常简单,只要从比较二个数列的第一个数,谁小就先取谁,取了后就在对应数列中删除这个数。然后再进行比较,如果有数列
插入排序算法有两层循环。外层循环会啄个遍历数组元素,而内存循环则会把外层循环所选择的元素与该元素在数组内的下一个元素进行比较。如果外层循环选择的元素小于内存循环选择的元素,那么瘦元素都想右移动以便为内存循环元素留出位置。 public void InsertionSort() { int inner, temp;
public int binSearch(int value) { int upperBround, lowerBound, mid; upperBround = arr.Length - 1; lowerBound = 0; while (lowerBound <= upper
虽然从表内第一个节点到最后一个节点的遍历操作是非常简单的,但是反向遍历链表却不是一件容易的事情。如果为Node类添加一个字段来存储指向前一个节点的连接,那么久会使得这个反向操作过程变得容易许多。当向链表插入节点的时候,为了吧数据复制给新的字段会需要执行更多的操作,但是当腰吧节点从表移除的时候就能看到他的改进效果了。 首先需要修改Node类来为累增加一个额外的链接。为了区别两个连接,这个把指
八、树(Tree)树,顾名思义,长得像一棵树,不过通常我们画成一棵倒过来的树,根在上,叶在下。不说那么多了,图一看就懂:当然了,引入了树之后,就不得不引入树的一些概念,这些概念我照样尽量用图,谁会记那么多文字?树这种结构还可以表示成下面这种方式,可见树用来描述包含关系是很不错的,但这种包含关系不得出现交叉重叠区域,否则就不能用树描述了,看图:面试的时候我们经常被考到的是一种叫“二叉树”的结构,二叉
Queue的实现: 就像Stack类的实现所做的一样,Queue类的实现用ArrayList简直是毋庸置疑的。对于这些数据结构类型而言,由于他们都是动态内置的结构,所以ArrayList是极好的实现选择。当需要往队列中插入数据项时,ArrayList会在表中把每一个保留的数据项向前移动一个元素。 class CQueue { private ArrayLis
来自:http://yingyingol.iteye.com/blog/13348911 快速排序介绍:快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序 n 个项目要Ο(n log n)次比较。在最坏状况下则需要Ο(n2)次比较,但这种状况并不常见。事实上,快速排序通常明显比其他Ο(n log n) 算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地
Stack的实现必须采用一种基本结构来保存数据。因为再新数据项进栈的时候不需要担心调整表的大小,所以选择用arrayList.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Collecti
数组类测试环境与排序算法using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Data_structure_and_algorithm{ class CArray { pr
一、构造二叉树 二叉树查找树由节点组成,所以需要有个Node类,这个类类似于链表实现中用到的Node类。首先一起来看看Node类的代码。 public class Node { public int Data; public Node Left; public Node Right; public v
二叉树是一种特殊的树。二叉树的特点是每个结点最多有两个儿子,左边的叫做左儿子,右边的叫做右儿子,或者说每个结点最多有两棵子树。更加严格的递归定义是:二叉树要么为空,要么由根结点、左子树和右子树组成,而左子树和右子树分别是一棵二叉树。 下面这棵树就是一棵二叉树。         二叉树的使用范围最广,一棵多叉树也可以转化为二叉树,因此我们将着重讲解二叉树。二叉树中还有连两种特殊的二叉树叫做满二叉树和
上一节中我们学习了队列,它是一种先进先出的数据结构。还有一种是后进先出的数据结构它叫做栈。栈限定只能在一端进行插入和删除操作。比如说有一个小桶,小桶的直径只能放一个小球,我们现在向小桶内依次放入2号、1号、3号小球。假如你现在需要拿出2号小球,那就必须先将3号小球拿出,再拿出1号小球,最后才能将2号小球拿出来。在刚才取小球的过程中,我们最先放进去的小球最后才能拿出来,而最后放进去的小球却可以最先拿
msdn中的描述如下:(?= 子表达式)(零宽度正预测先行断言。) 仅当子表达式在此位置的右侧匹配时才继续匹配。例如,w+(?=d) 与后跟数字的单词匹配,而不与该数字匹配。此构造不会回溯。(?(零宽度正回顾后发断言。) 仅当子表达式在此位置的左侧匹配时才继续匹配。例如,(?此构造不会回溯。msdn描述的比较清楚,如:w+(?=ing) 可以匹配以ing结尾的单词(匹配结果不包括ing),(
1.引入线索二叉树 二叉树的遍历实质上是对一个非线性结构实现线性化的过程,使每一个节点(除第一个和最后一个外)在这些线性序列中有且仅有一个直接前驱和直接后继。但在二叉链表存储结构中,只能找到一个节点的左、右孩子信息,而不能直接得到节点在任一遍历序列中的前驱和后继信息。这些信息只有在遍历的动态过程中才能得到,因此,引入线索二叉树来保存这些从动态过程中得到的信息。 2.建立线索二叉树 为了保
排序与我们日常生活中息息相关,比如,我们要从电话簿中找到某个联系人首先会按照姓氏排序、买火车票会按照出发时间或者时长排序、买东西会按照销量或者好评度排序、查找文件会按照修改时间排序等等。在计算机程序设计中,排序和查找也是最基本的算法,很多其他的算法都是以排序算法为基础,在一般的数据处理或分析中,通常第一步就是进行排序,比如说二分查找,首先要对数据进行排序。在Donald Knuth 的计算机程序设