二叉查找平衡树---再平衡旋转

本文详细介绍了AVL树的实现原理,包括节点插入、单旋转与双旋转操作,并提供了一个具体的Java实现示例。通过该示例,读者可以深入了解AVL树如何保持平衡以确保高效的数据检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class AvlTree {

public AvlTree() {

}

public static class AvlNode {
	int val;
	AvlNode left;
	AvlNode right;
	int height;

	AvlNode(int e) {
		val = e;
	}

	AvlNode(int e, AvlNode l, AvlNode r) {
		val = e;
		left = l;
		right = r;
		height = 0;
	}
}

public int getHeight(AvlNode node) {
	return node != null ? node.height : -1;
}

private AvlNode insert(int e, AvlNode t) {
	if (t == null) {
		return new AvlNode(e, null, null);
	}
	if (e < t.val) {
		t.left = insert(e, t.left);// insert to left child
		if (getHeight(t.left) - getHeight(t.right) == 2) {// have excel
			if (e < t.left.val) {
				t = rotateWithLeftChild(t);
			} else {
				t = doubleWithLeftChild(t);
			}
		}

	} else if (e > t.val) {
		t.right = insert(e, t.right);
		if (getHeight(t.right) - getHeight(t.left) == 2) {
			if (e > t.right.val) {
				t = rotateWithRightChild(t);
			} else {
				t = doubleWithRightChild(t);
			}
		}
	}
	t.height = Math.max(getHeight(t.left), getHeight(t.right)) + 1;
	return t;
}

private AvlNode rotateWithRightChild(AvlNode node) {
	AvlNode k1 = node.right;// k1是中间节点,最后返回k1
	node.right = k1.left;
	k1.left = node;
	node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
	k1.height = Math.max(getHeight(k1.right), getHeight(k1.left)) + 1;
	return k1;
}

private AvlNode rotateWithLeftChild(AvlNode k2) {
	AvlNode k1 = k2.left;
	k2.left = k1.right;
	k1.right = k2;
	k2.height = Math.max(getHeight(k2.left), getHeight(k2.right)) + 1;
	k1.height = Math.max(getHeight(k1.right), getHeight(k1.left)) + 1;
	return k1;
}

public AvlNode doubleWithLeftChild(AvlNode k3) {
	k3.left = rotateWithRightChild(k3.left);
	return rotateWithLeftChild(k3);
}

public AvlNode doubleWithRightChild(AvlNode k3) {
	k3.right = rotateWithLeftChild(k3.right);
	return rotateWithRightChild(k3);
}

public void firstRetrival(AvlNode root) {
	if(root == null) return;
	if (root.left != null) {
		firstRetrival(root.left);
	}
	System.out.println("" + root.val);
	if (root.right != null) {
		firstRetrival(root.right);
	}
}

public static void main(String[] args) {
	AvlTree tree = new AvlTree();
	AvlNode root = tree.insert(0, null);
	root = tree.insert(3, root);
	root = tree.insert(4, root);
	root = tree.insert(9, root);
	root = tree.insert(23, root);
	root = tree.insert(6, root);
	tree.firstRetrival(root);
	root = tree.insert(5, root);//
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值