AVL树

一棵AVL树是每个节点的左子树和右子树的高度最多差1的二叉查找树

每一个节点保留高度信息。

	//私有节点类
	private static class AvlNode<AnyType>{
		//构造器
		AvlNode(AnyType theElement){
			this(theElement, null, null);
		}
		AvlNode(AnyType theElement, AvlNode<AnyType> lt, AvlNode<AnyType> rt){
			element = theElement;
			left = lt;
			right = rt;
			height = 0;
		}
		
		AnyType element;
		AvlNode<AnyType> left;
		AvlNode<AnyType> right;
		int height;
	}
	
	//计算节点高度
	private int height(AvlNode<AnyType> t){
		return t == null ? -1 : t.height;
	}
	
	//插入节点
	private AvlNode<AnyType> insert(AnyType x, AvlNode<AnyType> t){
		
		if(t == null){
			return new AvlNode<AnyType>(x, null, null);
		}
		
		int compareResult = compare(x, t.element);
		
		if(compareResult < 0){
			t.left = insert(x, t.left);
			if(height(t.left) - height(t.right) == 2){
				if(compare(x, t.left.element) < 0){
					t = rotateWithLeftChild(t);
				}else{
					t = doubleWithLeftChild(t);
				}
			}
		}else if(compareResult > 0){
			t.right = insert(x, t.right);
			if(height(t.right) - height(t.left) == 2){
				if(compare(x, t.right.element) > 0){
					t = rotateWithRightChild(t);
				}else{
					t = doubleWithRightChild(t);
				}
			}
		}else{
			;//重复,不插入
		}
		
		t.height = Math.max(height(t.left), height(t.right)) + 1;
		
		return t;
	}
	
	//单旋转,左右对称
	private AvlNode<AnyType> rotateWithLeftChild(AvlNode<AnyType> k2){
		AvlNode<AnyType> k1 = k2.left;
		k2.left = k1.right;
		k1.right = k2;
		k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
		k1.height = Math.max(height(k1.left), k2.height) + 1;
		return k1;
	}
	
	//双旋转,左右对称
	private AvlNode<AnyType> doubleWithLeftChild(AvlNode<AnyType> k3){
		k3.left = retateWithRightChild(k3.left);
		return rotateWithLeftChild(k3);
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值